如何使用writeToFile将文件保存在文件目录中?

问题描述 投票:14回答:6
// 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))")
            }
        }

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

ios image swift writetofile
6个回答
1
投票

将图像放在NSData对象中;使用此类写入文件是轻而易举的,它会使文件大小变小。

顺便说一句,我推荐NSPurgeableData。保存图像后,您可以将对象标记为可清除,这将保留内存消耗。这可能是您的应用程序的问题,但可能与另一个你正在挤出。


0
投票

在Swift 4.2和Xcode 10.1中

func saveImageInDocsDir() {

    let image: UIImage? = yourImage//Here set your image
    if !(image == nil) {
        // get the documents directory url
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0] // Get documents folder
        let dataPath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("ImagesFolder").absoluteString //Set folder name
        print(dataPath)
        //Check is folder available or not, if not create 
        if !FileManager.default.fileExists(atPath: dataPath) {
            try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: true, attributes: nil) //Create folder if not
        }

        // create the destination file url to save your image
        let fileURL = URL(fileURLWithPath:dataPath).appendingPathComponent("imageName.jpg")//Your image name
        print(fileURL)
        // get your UIImage jpeg data representation
        let data = UIImageJPEGRepresentation(image!, 1.0)//Set image quality here
        do {
            // writes the image data to disk
            try data?.write(to: fileURL, options: .atomic)
        } catch {
            print("error:", error)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.