一尘不染

如何使用writeToFile将图像保存在文档目录中?

swift

// directoryPath is a URL from another VC
@IBAction func saveButtonTapped(sender: AnyObject) {
            let directoryPath           =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
            let urlString : NSURL       = directoryPath.URLByAppendingPathComponent("Image1.png")
            print("Image path : \(urlString)")
            if !NSFileManager.defaultManager().fileExistsAtPath(directoryPath.absoluteString) {
                UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.absoluteString, atomically: true)
                displayImageAdded.text  = "Image Added Successfully"
            } else {
                displayImageAdded.text  = "Image Not Added"
                print("image \(image))")
            }
        }

我没有收到任何错误,但是图像没有保存在文档中。


阅读 275

收藏
2020-07-07

共1个答案

一尘不染

那里的问题是您正在检查文件夹是否不存在,但是应该检查文件是否存在。代码中的另一个问题是,您需要使用url.path而不是url.absoluteString。您还将使用“
png”文件扩展名保存jpeg图像。您应该使用“ jpg”。

编辑/更新:

Swift 4.2或更高版本

// get the documents directory url
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// choose a name for your image
let fileName = "image.jpg"
// create the destination file url to save your image
let fileURL = documentsDirectory.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
if let data = image.jpegData(compressionQuality:  1.0),
  !FileManager.default.fileExists(atPath: fileURL.path) {
    do {
        // writes the image data to disk
        try data.write(to: fileURL)
        print("file saved")
    } catch {
        print("error saving file:", error)
    }
}
2020-07-07