How to save image

前端 未结 3 1067
挽巷
挽巷 2021-01-27 09:27

I want to save image with userdefaults and use it in another view with this code but it shows an error .

UserDefaults.standard.set(img , forKey : \"simg\")
         


        
3条回答
  •  独厮守ぢ
    2021-01-27 09:49

    This is how I would do it. You have multiple places to save it to, the user's Documents folder is usually best:

    func cacheImageAsPNG(image: UIImage, localID: String) {
        let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        if let imageData = UIImagePNGRepresentation(image) {
            let filename = userDocumentsURL.appendingPathComponent("\(localID).png")
    
            if  FileManager.default.createFile(atPath: filename.path, contents: imageData, attributes: nil) {
                print("wrote file:\n\(filename.path)")
            } else {
                print("couldn't write the file:\n\(filename.path)")
            }
        }
    }
    

    if you want it erased by the system during times of peak memory usage, the cache directory is a better place:

     let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
    

    Edit: Retrieving the Image

    func cachedImage(localID: String) -> UIImage? {
        let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let cachePath = userDocumentsURL.appendingPathComponent("\(localID).png")
    
        return UIImage(named: cachePath.path)
    }
    

提交回复
热议问题