I've killed a few days trying to save a file and list it in a home directory.
First I retrieve a home directory URL. I tried two options:
docDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
docDir = URL(fileURLWithPath: NSHomeDirectory())
In any way when running on simulator or my iPhone it results in just file:///
Well, maybe that's ok for sandboxed iOS app...
After that I prepare a file URL. I tried two ways:
let file = docDir.appendingPathComponent("myfile.tmp")
let file = URL(fileURLWithPath: "myfile.tmp")
print(file.absoluteURL)
Here I get file:///myfile.tmp (in both variants)
Finally I try to create file
do {
try Data(count: 0).write(to: file2)
}
catch {
print("Failed to create file: '\(file)' because of: \(error)")
}
And here is what I get
On simulator:
Failed to create file: './myfile.tmp -- file:///' because of: Error Domain=NSCocoaErrorDomain Code=642 "You can’t save the file “myfile.tmp” because the volume “AirHD — данные” is read only." UserInfo={NSFilePath=/myfile.tmp, NSUnderlyingError=0x600000dea1f0 {Error Domain=NSPOSIXErrorDomain Code=30 "Read-only file system"}}
On iPhone:
Failed to create file: './myfile.tmp -- file:///' because of: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “myfile.tmp” in the folder “System”." UserInfo={NSFilePath=/myfile.tmp, NSUnderlyingError=0x281725a40 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
But why in the folder “System” ?? It should have been my Documents folder!
UPD: setting keys UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace in Info.plist file did not help also.
URL(fileURLWithPath: NSHomeDirectory())is wrong - Leo Dabuslet fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("file.txt")and thentry Data([97,98,99]).write(to: fileURL, options: .atomic). This will create a text file with an abc string content - Leo Dabus