1

I create an array in swift like so:

var imagesArray = [String]()

and I add some base64 images to that array like so:

imagesArray.append(imageBase64String!)

Now I need to create a text.txt file and write the imagesArray into that file so I can send it to the server.

I tried this:

let fileName = "myFile.txt"
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

let data = Data(imagesArray)
do {
    try data.write(to: url, options: .atomic)
    print(url)
} catch {
    print(error)
}

But this produces this error:

No exact matches in call to initializer 

which is infant of this code: let data = Data(imagesArray)

could someone please advice on this issue?

1 Answer 1

2

There's no built-in initializer for Data that takes in a [String]. imagesArray is a [String], so it doesn't work.

How do you want to save the array of Strings? If you want a new line between each String, you can try something like this (no need to use Data, instead, combine the array into 1 string):

let fileName = "myFile.txt"
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

let joinedImagesArray = imagesArray.joined(separator: "\n") /// separated by newline
do {
    try joinedImagesArray.write(toFile: url.path, atomically: true, encoding: .utf8)
    print(url)
} catch {
    print(error)
}
Sign up to request clarification or add additional context in comments.

4 Comments

the code you've provided throws a few errors!
This works with no error: try joinedStrings.write(toFile: outputURL.path, atomically: true, encoding: .utf8)
@rooz far glad you figured it out! I didn’t test my answer, should have.
iOS 10+ you can simply use FileManager.default.temporaryDirectory. Btw there is also a URL version of the write method. write(to: url, ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.