问题描述
我在从UIImagePickerControllerImageURL中保存和检索UserDefaults中的数组时遇到问题.同步后可以获取数组,但是无法检索它.myArray为空.
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.
testImage.image确实获得了图像,在那里没有问题.
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)
}
推荐答案
这里有很多问题.
- 请勿使用
NSData
,而应使用Data
. - 请勿使用
NSMutableArray
,而应使用Swift数组. - 您可以直接从
info
字典中获取UIImage
. - 您不能将URL存储在
UserDefaults
中. - 在使用新的URL更新阵列之前,将
array
保存到UserDefaults
. - 您创建一个新数组,而不是从
UserDefaults
获取当前数组. - 您不必要地调用
同步
. - 您无需为大多数变量指定类型.
- Do not use
NSData
, useData
. - Do not use
NSMutableArray
, use a Swift array. - You can get the
UIImage
directly from theinfo
dictionary`. - You can't store URLs in
UserDefaults
. - You save
array
toUserDefaults
before you update the array with the new URL. - You create a new array instead of getting the current array from
UserDefaults
. - You needlessly call
synchronize
. - 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)
}
请注意,这会保存代表每个URL的字符串数组.稍后,当您访问这些字符串时,如果需要 URL
,则需要使用 URL(string:arrayElement)
.
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)
.
这篇关于在Swift中从ImagePickerControllerImageURL在UserDefaults中保存并追加一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!