如何使用writeToFile将文件保存在文件目录中? [英] how to use writeToFile to save image in document directory?

查看:1352
本文介绍了如何使用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))")
            }
        }

我没有收到任何错误但图片没有保存在t中他的文件。

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 you should check the file exists. Also you should 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

// 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 = UIImageJPEGRepresentation(image, 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将文件保存在文件目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆