Load and save image from document directory

I have added two methods to an extension of URL so I can load and save and images.
Code Block Swift
extension URL {
func loadImage(_ image: inout UIImage) {
if let loaded = UIImage(contentsOfFile: self.path) {
image = loaded
}
}
func saveImage(_ image: UIImage) {
if let data = image.jpegData(compressionQuality: 1.0) {
try? data.write(to: self)
}
}
}

I use this extension in a view:
Code Block Swift
@State private var image = UIImage(systemName: "xmark")!
private var url: URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0].appendingPathComponent("image.jpg")
}
var body: some View {
Image(uiImage: image)
.onAppear {
url.load(&image)
}
.onTapGesture {
url.save(image)
}
}

However this isn't working.
The image isn't loaded from the document directory because its probably isn't being saved.

Is there anyway to rewrite this extension or another alternative to loading and saving a UIImage?
Or is this just a bug with Xcode 12/iOS 14?
Answered by BabyJ in 638454022
I have this working now with this:
Code Block Swift
extension URL {
func loadImage(_ image: inout UIImage?) {
if let data = try? Data(contentsOf: self), let loaded = UIImage(data: data) {
image = loaded
} else {
image = nil
}
}
func saveImage(_ image: UIImage?) {
if let image = image {
if let data = image.jpegData(compressionQuality: 1.0) {
try? data.write(to: self)
}
} else {
try? FileManager.default.removeItem(at: self)
}
}
}

I added this to the loadImage method and it does work.
Code Block Swift
func loadImage(_ image: inout UIImage) {
if let data = Data(contentsOf: self), let loaded = UIImage(data: data) {
image = loaded
}
}

However it takes a long time for the image to be saved: after tapping on the image for it to be saved, quitting the app, and then opening it again the image hadn’t been saved.
If I kept tapping on the image, then quit and reopened the app the image had been saved.

Is there a way to add a progress indicator until the image has been saved successfully, or a better way to load and save images?
Accepted Answer
I have this working now with this:
Code Block Swift
extension URL {
func loadImage(_ image: inout UIImage?) {
if let data = try? Data(contentsOf: self), let loaded = UIImage(data: data) {
image = loaded
} else {
image = nil
}
}
func saveImage(_ image: UIImage?) {
if let image = image {
if let data = image.jpegData(compressionQuality: 1.0) {
try? data.write(to: self)
}
} else {
try? FileManager.default.removeItem(at: self)
}
}
}

Its all works! Thank you so much! The easiest way to store profile image

Load and save image from document directory
 
 
Q