I have added two methods to an extension of URL so I can load and save and images.
I use this extension in a view:
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?
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?
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) } } }