Search code examples
fileswift3tvos

TVOS FileManager's createFile fails with error 1


I'm trying to create a json file on a Apple TV device to save some data but createFile(...) always fails, returning false. I've tried with absolutePath, relativePath and path to no success. The jsonData variable is created just fine in my implementation and it works on the Simulator:

self.fileName = "MyFileTest"
self.directory = .documentDirectory

let documentsDirectory = fileManager.urls(for: self.directory, in: .userDomainMask)[0]

self.fullyQualifiedPath = documentsDirectory.appendingPathComponent(self.fileName).appendingPathExtension("json").path

do {
    let jsonData = try convertObjectToData(data: dataForJson)
    if !fileManager.createFile(atPath: fullyQualifiedPath, contents: jsonData as Data, attributes: nil) {
        print("File Manager failed at createFile")
        throw FileErrors.FileNotSaved
    }
} catch {
    print("Unable to create json file \(error.localizedDescription)")
    throw FileErrors.FileNotSaved
}

Here createFile fails and returns false and the following is printed out:

File Manager failed at createFile Unable to create json file The operation couldn’t be completed. (TestAppTVOS.FileSaveHelper.(FileErrors in _70D0A1275AC2AFFFA4ED048E3A809030) error 1.)

The fullyQualifiedPath variable value is:

/var/mobile/Containers/Data/Application/00DCB709-5EC6-40FC-BB21-D797EB4FE2F5/Documents/MyFileTest.json

Not sure what to make out of that error message "The operation couldn’t be completed" and "error 1"? Any ideas how to get this working properly for Swift 3?


Solution

  • After spending a bit too much time on this it seems it was related to which folder I was creating the file in.

    As I am in sandbox mode/debugging I could not write to the Documents folder so instead had to switch to the Cache folder.

    E.g

    self.directory = .cachesDirectory
    

    Works now.