我在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)
}
答案 0 :(得分:0)
这里有很多问题。
NSData
,请使用Data
。NSMutableArray
,请使用Swift数组。UIImage
字典`获取info
。UserDefaults
。array
保存到UserDefaults
。UserDefaults
获取当前数组。synchronize
。以下是您更新的代码,以解决所有这些问题:
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)
。