Home > database >  Cannot write Data to file in Swift
Cannot write Data to file in Swift

Time:11-13

I have an image that I want it's data to be saved in this fileUri generated by ("react-native-fs"). LibraryDirectoryPath/saved_images/{filename}:

/Users/macbookpro/Library/Developer/CoreSimulator/Devices/9CBD2F1E-7330-418D-81BE-108C064DEA7E/data/Containers/Data/Application/C26348CC-3463-43EF-9B26-B7E31641E2EA/Library/saved_images/6B3A6A3A-8DE3-488B-AF43-A54775545B38.jpg

And below is my implementation:

do {
    let url = URL(string: fileUri)
    let fileExisted = FileManager().fileExists(atPath: url!.path)
    
    if (fileExisted) {
        try decryptedData.write(to: url!)
    } else {
        let handle = try FileHandle(forWritingTo: url!)
        handle.write(data) // data is type Data
        handle.closeFile()
    }
} catch {
    reject("FileError", "Failed to write file", error)
}

I also tried let url = URL(fileURLWithPath: fileUri) with and without file:// prepending to fileUri

do {
    let url = URL(fileURLWithPath: fileUri)
    let fileExisted = FileManager().fileExists(atPath: url.path)
    
    if (fileExisted) {
        try decryptedData.write(to: url)
    } else {
        let handle = try FileHandle(forWritingTo: url)
        handle.write(data)
        handle.closeFile()
    }
} catch {
    reject("FileError", "Failed to write file "   error.localizedDescription, error)
}

it says:

enter image description here

CodePudding user response:

You are using the wrong API.

let url = URL(string: fileUri)

is for strings representing a full – even encoded - URL starting with a scheme like file:// or https://.

On the other hand fileUri is actually a path without a scheme, so you have to use

let url = URL(fileURLWithPath: fileUri)

This returns a non optional URL by adding the file:// scheme.

fileUri should be renamed as filePath.

  • Related