0

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!

JPJerry5
  • 107
  • 10
  • Does this answer your question? [Attempt to insert non-property list object when trying to save a custom object in Swift 3](https://stackoverflow.com/questions/41355427/attempt-to-insert-non-property-list-object-when-trying-to-save-a-custom-object-i) – pawello2222 Jun 24 '20 at 23:31
  • Thank you I saw this before that did not help me. – JPJerry5 Jun 25 '20 at 08:34

1 Answers1

1

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
vadian
  • 274,689
  • 30
  • 353
  • 361