Save UIImage array in NSUserDefaults

后端 未结 4 1065
栀梦
栀梦 2021-01-26 00:30

I want to put a UIImage array into UserDefaults and then retrieve it. After that set the retrieved images in an image view. How can I do that?

4条回答
  •  有刺的猬
    2021-01-26 00:46

    That's really bad idea if you really going to do that. You should save image in DocumentDirectory and save images name in NSUserDefaults.

    func saveImages(images:[UIImage]) {
    
         let fileManager = FileManager.default
         let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) 
         var imagesNames = [String]()
    
    
        do {
    
            if !fileManager.fileExists(atPath: path as String){
                try fileManager.createDirectory(atPath: path as String, withIntermediateDirectories: true, attributes: nil)
            }
    
         for (index,image) in images.enumarated() {
            let imageName = "Image\(index).jpg"
            let imageData = UIImageJPEGRepresentation(image, 1.0)
            if fileManager.createFile(atPath: paths.appending("/\(file)") as String, contents: imageData, attributes: nil) {
             imagesNames.append(imageName)
            }
          }
         let storage = UserDefaults.standard
         storage.set(imagesNames, forKey: "imagesArray")
         storage.synchronize()
    
        }catch{
            //Throw Error
        } 
    }
    

提交回复
热议问题