Can not save file inside tmp directory

前端 未结 1 363
粉色の甜心
粉色の甜心 2020-11-29 13:19

I have this function to save an image inside the tmp folder

private func saveImageToTempFolder(image: UIImage, withName name: String) {

    if let data = UI         


        
相关标签:
1条回答
  • 2020-11-29 14:03

    absoluteString is not the correct method to get a file path of an NSURL, use path instead:

    let targetPath = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").path!
    data.writeToFile(targetPath, atomically: true)
    

    Or better, work with URLs only:

    let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg")
    data.writeToURL(targetURL, atomically: true)
    

    Even better, use writeToURL(url: options) throws and check for success or failure:

    do {
        try data.writeToURL(targetURL, options: [])
    } catch let error as NSError {
        print("Could not write file", error.localizedDescription)
    }
    

    Swift 3/4 update:

    let targetURL = tempDirectoryURL.appendingPathComponent("\(name).jpg")
    do {
        try data.write(to: targetURL)
    } catch {
        print("Could not write file", error.localizedDescription)
    }
    
    0 讨论(0)
提交回复
热议问题