Search code examples
iosswiftdictionaryurlnsuserdefaults

Getting an error when I try to store a dictionary using user defaults


I am downloading images and adding the url of the image with an integer to my dictionary. When the view is about to disappear I want to store the data using the user defaults. Unfortunately I am getting the error: "Attempt to insert non-property list object ...", which is shown in the image. I do not understand why I get this error.

enter image description here

This is the code I used to download the images and set up the dictionary.

var imageURLS = [Int: String]()

func downloadImage(url: URL) {
        let dataTask = URLSession.shared.dataTask(with: url) { data, responseURL, error in
            
            var downloadedImage:UIImage?

            if let data = data {
                downloadedImage = UIImage(data: data)
            }
            // if download actaully got an image
            if downloadedImage != nil {
                self.sum += 1 // increase the sum by one
                self.cache.setObject(downloadedImage!, forKey: url.absoluteString as NSString) // cache the image
                // add the sumas key
                // add the url as value to the dictionary
                self.imageURLS[self.sum] = url.absoluteString
            }
        }
        dataTask.resume()
    }

And this is my code to store and recall the dictionary.

override func viewWillDisappear(_ animated: Bool) {
        UserDefaults.standard.set(imageURLS, forKey: "imageUrlDictionary")
}

override func viewWillAppear(_ animated: Bool) {
        imageURLS = UserDefaults.standard.object(forKey: "imageUrlDictionary") as? [Int:String] ?? [:]
}

Thank you very much for your help and suggestions!


Solution

  • The reason of the error is that property list keys are required to be String.

    You could to convert the Int values to String

    var imageURLS = [String: String]()
    
    ...
    
    self.imageURLS[String(self.sum)] = url.absoluteString