Save and Append an Array in UserDefaults from ImagePickerControllerImageURL in Swift

橙三吉。 提交于 2019-12-13 02:46:13

问题


I'm having an issue saving and retrieving an array in UserDefaults from UIImagePickerControllerImageURL. I can get the array after synchronizing, but I am unable to retrieve it. myArray is empty.

The testImage.image does get the image, no problems there.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let imageURL: URL = info[UIImagePickerControllerImageURL] as! URL

    //test that imagepicker is actually getting the image
    let imageData: NSData = try! NSData(contentsOf: imageURL)
    let cvImage = UIImage(data:imageData as Data)
    testImage.image = cvImage

    //Save array to UserDefaults and add picked image url to the array
    let usD = UserDefaults.standard
    var array: NSMutableArray = []
    usD.set(array, forKey: "WeatherArray")
    array.add(imageURL)
    usD.synchronize()
    print ("array is \(array)")

    let myArray = usD.stringArray(forKey:"WeatherArray") ?? [String]()
    print ("myArray is \(myArray)")

    picker.dismiss(animated: true, completion: nil)
}

回答1:


There are many issue here.

  1. Do not use NSData, use Data.
  2. Do not use NSMutableArray, use a Swift array.
  3. You can get the UIImage directly from the info dictionary`.
  4. You can't store URLs in UserDefaults.
  5. You save array to UserDefaults before you update the array with the new URL.
  6. You create a new array instead of getting the current array from UserDefaults.
  7. You needlessly call synchronize.
  8. You needlessly specify the type for most of your variables.

Here is your code updated to fix all of these issues:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        testImage.image = image
    }

    if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
        //Save array to UserDefaults and add picked image url to the array
        let usD = UserDefaults.standard
        var urls = usD.stringArray(forKey: "WeatherArray") ?? []
        urls.append(imageURL.absoluteString)
        usD.set(urls, forKey: "WeatherArray")
    }

    picker.dismiss(animated: true, completion: nil)
}

Note that this saves an array of strings representing each URL. Later on, when you access these strings, if you want a URL, you need to use URL(string: arrayElement).



来源:https://stackoverflow.com/questions/48142238/save-and-append-an-array-in-userdefaults-from-imagepickercontrollerimageurl-in-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!