I’m relatively new to coding and I’m working on an app where users need to be able to redraw or edit their previous drawings. To accomplish this, I’ve been saving the drawings on the backend by taking a screenshot of the view using the following extension:
extension UIView {
func screenShot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
defer { UIGraphicsEndImageContext() }
drawHierarchy(in: bounds, afterScreenUpdates: true)
return UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
}
}
However, I’m not sure how to load these saved images back into the PKDrawingView for users to edit. I’ve been researching and experimenting, but as a beginner, I’m still finding my way around.
Below is the method I am trying.
@IBOutlet weak var mCanvasView: PKCanvasView!
...
func loadImageFromURL(_ urlString: String) {
// Check if URL is valid
guard let url = URL(string: urlString) else {
print("Invalid URL")
return
}
// Asynchronously load data from URL
let task = URLSession.shared.dataTask(with: url) { data, response, error in
// Check for errors or missing data
guard let data = data, error == nil else {
if let error = error {
print("Error loading data: (error)")
}
return
}
// Process the data on the main queue
DispatchQueue.main.async {
// Check if the URL points to an SVG file
if urlString.contains(".svg") {
print("PKdrawing Error: SVG files are not supported")
} else {
// Try to create UIImage and convert it to PNG data
if let uiImage = UIImage(data: data), let pngData = uiImage.pngData() {
do {
// Set the PKDrawing if UIImage conversion is successful
self.mCanvasView.drawing = try PKDrawing(data: pngData)
} catch {
print("PKdrawing Error: (error)")
}
} else {
print("PKdrawing Error: Failed to create UIImage or PNG data")
}
}
}
}
// Start the data task
task.resume()
}
New contributor
Sumit Meena is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.