How do I write a subclass of UIDocument for a png file?

I have a subclass of UIDocument that I would like the code to be checked. Here it is. Did I do this properly? I think I did but I'm running into problems. I think this code should work as long as I save the file to a url with a png extension.


UIDocument subclass:

class ImageDocument: UIDocument {
    
    var image: UIImage? = nil
    
    override func load(fromContents contents: Any, ofType typeName: String?) throws {
        
        guard let data = contents as? Data else {
            
            throw DataFileError.fileReadFailed
            
        }
        
        image = UIImage(data: data)
        
    }
    
    override func contents(forType typeName: String) throws -> Any {
        
        guard image != nil else {
            
            throw DataFileError.badData
            
        }
        
        return image!.pngData() as Any
        
    }

}


Code to save using UIDocument subclass:

saveToURL.appendPathExtension("png")

let document = ImageDocument(fileURL: saveToURL)

document.image = image // UIImage object

document.save(to: document.fileURL, for: .forCreating) {
    
    (success: Bool) in
    
    print("document.save success - ", success)
    
    print("document.fileURL=", document.fileURL)
    
}