【问题标题】:Save and Append an Array in UserDefaults from ImagePickerControllerImageURL in Swift从 Swift 中的 ImagePickerControllerImageURL 保存并附加一个数组到 UserDefaults
【发布时间】:2018-06-16 22:57:02
【问题描述】:

我在从 UIImagePickerControllerImageURL 保存和检索 UserDefaults 中的数组时遇到问题。同步后我可以得到数组,但我无法检索它。 myArray 为空。

testImage.image 确实得到了图像,没有问题。

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)
}

【问题讨论】:

    标签: arrays swift nsuserdefaults


    【解决方案1】:

    这里有很多问题。

    1. 不要使用NSData,使用Data
    2. 不要使用NSMutableArray,使用 Swift 数组。
    3. 您可以直接从info 字典中获取UIImage
    4. 您不能将 URL 存储在 UserDefaults 中。
    5. 在使用新 URL 更新数组之前,将 array 保存到 UserDefaults
    6. 您创建了一个新数组,而不是从 UserDefaults 获取当前数组。
    7. 你不必要地打电话给synchronize
    8. 您无需为大多数变量指定类型。

    您的代码已更新以解决所有这些问题:

    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)
    }
    

    请注意,这会保存代表每个 URL 的字符串数组。稍后,当你访问这些字符串时,如果你想要一个URL,你需要使用URL(string: arrayElement)

    【讨论】:

    • 我有一个关于访问字符串的后续问题。你介意看看here@rmaddy吗?
    猜你喜欢
    • 2019-09-15
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多