Display image from app container in UIImageView

Hi all.

I have a UserDefaults dictionary that contains a URL to an image (.png) saved on-device.

Code Block Swift
let dict = defaults.object(forKey: myString) as? [String: String] ?? [String: String]()
let imgStr = dict["Image"]

This returns a string with the file path of the image on the device, as saved from another View Controller:
Code Block text
file:///Users/noah/Library/Developer/CoreSimulator/Devices/60EB1F35-0B0A-4E65-B891-FE157B2D2AD7/data/Containers/Data/Application/60A8DC12-7636-4D47-BCC2-DA1BA55703CE/Documents/MyString.png

I then need to display this image in an image view: this code is what I have:
Code Block Swift
let imgToDisplay = UIImage(contentsOfFile: imgStr!)
imageView.image = imgToDisplay

This doesn't cause any errors, but the image view displays nothing — not even the placeholder image in my Storyboard.

I do have
Code Block Swift
override func viewDidLoad() {
super.viewDidLoad()
imageView.isHidden = false
}

earlier in the file and
Code Block Swift
if imgStr == "NO_IMAGE_UPLOADED" {
imageView.isHidden = true
}

The "NO_IMAGE_UPLOADED" string is what another View Controller saves in place of the image path when an image is being uploaded. Not the prettiest way, but it works for now.


In short, the issue is that the image view displays nothing, even when my print statements through the program all get executed. Even my storyboard placeholder image doesn't display.

Thanks in advance for any help you can give me and I hope you're all well.



Do not store absolute paths, and that includes absolute URLs, that point inside your app’s container. The problem is that the absolute path to the container itself can change from run-to-run [1].

Rather than storing an absolute path you should store:
  • A bookmark

  • A relative path, relative to some point within your container, like the root of the container, the Documents directory, and so on

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"

[1] The exact rules as to when this will change are not documented, and have varied over time.
Display image from app container in UIImageView
 
 
Q