I saved the image URL in userdefault, and then I read it, but I can't view it inside UIImageView
print("UserDefaults url: \(String(describing: defaults.url(forKey: "urlPhoto")))")
file:///var/mobile/Containers/Data/Application/HI5648UUU-B7777-9999-4444-KUG6546848/Documents/landscape.png
@IBOutlet weak var photoUser: UIImageView!
photoUser.image = (defaults.data(forKey: "urlPhoto") ?? UIImage(named: "photoPlaceholder")) as? Data
if userdefault is empty then load photoPlaceholder
You shouldn't do that, because the path of the URL HI5648UUU-B7777-9999-4444-KUG6546848
always changes after each launch.
The better approach is to cache the suffix and the file extension only, which in this case is landscape.png
, to .documentDirectory
. And then load it with:
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let urlPhoto = UserDefaults.standard.string(forKey: "urlPhoto")
if let urlPhoto, let fullPath = documentDirectory?.appendingPathComponent(urlPhoto) {
return UIImage(contentsOfFile: fullPath.path)
} else {
return UIImage(named: "photoPlaceholder")
}