简体   繁体   English

将UIImage数组保存在NSUserDefaults中

[英]Save UIImage array in NSUserDefaults

I want to put a UIImage array into UserDefaults and then retrieve it. 我想将UIImage数组放入UserDefaults ,然后检索它。 After that set the retrieved images in an image view. 之后,在图像视图中设置检索到的图像。 How can I do that? 我怎样才能做到这一点?

First of all that is not ideal way to save image in user default but if you want you can do following things 首先,这不是在用户默认状态下保存图像的理想方法,但是如果您愿意,可以执行以下操作

Save

let imageData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(imageData, forKey: "images")

Retrieve 取回

       let imageData = UserDefaults.standard.object(forKey: "images") as? NSData

        if let imageData = imageData {
            let imageArray = NSKeyedUnarchiver.unarchiveObject(with: imageData as Data) as? [UIImage]!
            print(placesArray)
        }

Note: You should save your image in document directory and then save that name array to user default. 注意:您应该将图像保存在文档目录中,然后将该名称数组保存为用户默认设置。

Save image in document directory 将图像保存在文档目录中

func saveImageDocumentDirectory(){
        let fileManager = NSFileManager.defaultManager()
        let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("apple.jpg")
        let image = UIImage(named: "apple.jpg")
        print(paths)
        let imageData = UIImageJPEGRepresentation(image!, 0.5)
        fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
    }

Retrieve image 检索图像

func getImage(name : String){
        let fileManager = NSFileManager.defaultManager()
        let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent(name)
        if fileManager.fileExistsAtPath(imagePAth){
            self.imageView.image = UIImage(contentsOfFile: imagePAth)
        }else{
            print("No Image")
        }
    }

func getDirectoryPath() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

That's really bad idea if you really going to do that. 如果您真的要这样做,那真是个坏主意。 You should save image in DocumentDirectory and save images name in NSUserDefaults . 您应该将图像保存在DocumentDirectory中 ,并将图像名称保存在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
    } 
}

Simple approach, convert UIImages to NSData. 简单的方法,将UIImages转换为NSData。 Then add image data's into an NSArray. 然后将图像数据添加到NSArray中。 Then save the NSArray into UserDefault. 然后将NSArray保存到UserDefault中。 When retrieving the NSArray from UserDefault,use ImageWithData method to render UIImage from the NSArray's each elements. 从UserDefault检索NSArray时,请使用ImageWithData方法从NSArray的每个元素中呈现UIImage。 This is the easiest process if you really one to use UserDefaults for your purpose. 如果您确实是出于目的使用UserDefaults,这是最简单的过程。 Try this yourself. 自己尝试一下。

You can easily save your image in documentDirectory as below: 您可以轻松地将图像保存在documentDirectory中,如下所示:

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let fileURL = documentDirectory?.appendingPathComponent(yourImageName)

and then, you can give your image to UserDefaults 然后,您可以将图像提供给UserDefaults

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM