daniel
daniel

Reputation: 966

How do I write a file in iOS using FileManager?

I have the following code with the results of the print statements in comments beside the statements:

    let myImageData = FileManager.default.contents(atPath: myURL.absoluteString)

    var mySaveToURL: URL = FileManager.default.url(forUbiquityContainerIdentifier: nil)!
    mySaveToURL.appendPathComponent(myURL.pathComponents.last!)

    print("mySaveToURL=", mySaveToURL) // mySaveToURL= file:///Users/shinehah/Library/Developer/CoreSimulator/Devices/693D4940-1B91-43E1-B5AD-88E9763046C7/data/Library/Mobile%20Documents/iCloud~us~gnolaum~TrialNotifications/ABF236AE-A6E7-403E-ADC4-5BAA5DC734B3.jpeg


    let resultCreateFile = FileManager.default.createFile(atPath: mySaveToURL.absoluteString, contents: myImageData, attributes: nil)

    print("resultCreateFile=", resultCreateFile) // resultCreateFile= false


    do {

        try FileManager.default.copyItem(at: myURL, to: mySaveToURL)

        print("copy success!") // copy success!

    } catch {

        print(error.localizedDescription)

    }

As you can see I am not able to successfully execute the createFile() method of FileManager but was able to successfully execute the copyItem() method to the same URL.

What do I check to be able to figure out how to get the createFile() method to work?

Upvotes: 0

Views: 1462

Answers (1)

vadian
vadian

Reputation: 285260

The error occurs because you are using the wrong API. To get the path of a file system URL you have to use path.

let resultCreateFile = FileManager.default.createFile(atPath: mySaveToURL.path, contents: myImageData, attributes: nil)

However there is no reason to create the file explicitly. Just copy the other file.

Upvotes: 2

Related Questions