0
votes

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.

1
URL(fileURLWithPath: NSHomeDirectory()) is wrong - Leo Dabus
try let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("file.txt") and then try Data([97,98,99]).write(to: fileURL, options: .atomic). This will create a text file with an abc string content - Leo Dabus
Thank you! Your comment did help me to find the problem! - Baywind

1 Answers

0
votes

After more enquiries I found the problem! It was because I wrapped my docDir into a @State modifier Actually it was

@State var docDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

And for some reason this modifier turned actual URL to file:///