Swift's FileManager.default.url not creating files, keeps throwing errors

292 Views Asked by At

I've written these two function

func locallySave(_ data: Data?, for utility: Utility) throws {
    var fileURL = try FileManager.default.url(for: .applicationSupportDirectory,
                                               in: .userDomainMask,
                                               appropriateFor: nil,
                                               create: true)
    fileURL.appendPathComponent(Constants.appShortName)
    fileURL.appendPathComponent("\(utility).json")
    do {
        try data?.write(to: fileURL)
    } catch {
        print("Error: \(error)")
        throw error
    }
}

and

func locallyLoad(_ utility: Utility) throws -> Data? {
    var fileURL = try FileManager.default.url(for: .applicationSupportDirectory,
                                               in: .userDomainMask,
                                               appropriateFor: nil,
                                               create: false)
    fileURL.appendPathComponent(Constants.appShortName)
    fileURL.appendPathComponent("\(utility).json")
    do {
        let data = try Data(contentsOf: fileURL)
        return data
    } catch {
        print("Error: \(error)")
        throw error
    }
}

I think I've got one of two potential bugs in these function.

The first is that I've set create: true in the save function which should make it so if there isn't any file/directory, it will create them. The second is that it might be creating them, but whenever I run the app, the directory (in the simulator) seems to be changing so I don't know if it's ever going to pull the file if it is there.

For example if I run the app, it will say the URL is something like /Users/<MyUsername>/Library/Developer/CoreSimulator/Devices/C78E5655-0A29-4FA6-9EC3-20317881C18F/data/Containers/Data/Application/17F82456-9C7A-4D67-988E-88843B3446D8/Library/Application Support/AppTemplate/<SomeUtility>.json but if I run the app again, I'll get something like /Users/<MyUsername>/Library/Developer/CoreSimulator/Devices/C78E5655-0A29-4FA6-9EC3-20317881C18F/data/Containers/Data/Application/0397D6F1-94EC-4EF2-9F3C-68764109F845/Library/Application Support/AppTemplate/<SomeUtility>.json Notice how the second string of digits is completely different.

I don't think it's all the second error because where I go to the fileURL in finder, there's nothing there and it doesn't look like anything has been created at all.

The fileURL in both functions always comes out to be the same for both functions in the debugger. How do I get FileManager to create the file if it doesn't exist and how do I make sure it's always pulling from the same directory it will have saved to?

The error I get is NSUnderlyingError=0x600000fb0480 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

Thanks

0

There are 0 best solutions below