Search code examples
iosswiftuiimageviewuiimage

Unable to set <UIImage:0x283942880 anonymous {1080, 1080} renderingMode=automatic> to UIImageView XCode Swift


I have built an app which fetches contacts from phonebook and saves their name and photo. To save the photo I've used the following code

if let imageData = contact.thumbnailImageData {
                            
     imageStr = String(describing: UIImage(data: imageData)!)
                            
} else {
                        
     imageStr = "null"
}

and when I print imageStr using print("IMGSTR: \(imageStr)") I get the following output

IMSTR: <UIImage:0x283942880 anonymous {1080, 1080} renderingMode=automatic>

Now I'm stuck on how to set this string to the UIImageView, I tried

imageview.image = UIImage(named: imageStr)

but it shows nothing

Could someone please help me in how to set the string <UIImage:0x283942880 anonymous {1080, 1080} renderingMode=automatic> to UIImageView?


Solution

  • No need to convert it to a String. UserDefaults supports Data objects. Store it as Data and when setting it to a UIImageView use let image = UIImage(data : imageData)

    If you want to convert an instance of Data to String, you should use the String(decoding:as:) initializer, like this.(eg : let str = String(decoding: data, as: UTF8.self)).