本文介绍了如何使用 writeToFile 将图像保存在文档目录中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// 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))")
}
}
我没有收到任何错误,但图像没有保存在文档中.
I am not getting any error but the Image is not getting saved in the document.
推荐答案问题是您正在检查文件夹是否不存在,但您应该检查文件是否存在.代码中的另一个问题是您需要使用 url.path 而不是 url.absoluteString.您还使用png"文件扩展名保存 jpeg 图像.你应该使用jpg".
The problem there is that you are checking if the folder not exists but you should check if the file exists. Another issue in your code is that you need to use url.path instead of url.absoluteString. You are also saving a jpeg image using a "png" file extension. You should use "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) } }更多推荐
如何使用 writeToFile 将图像保存在文档目录中?
发布评论