How to create a Swift URL object from Data (byte array) without writing the bytes to disk?
Background:
I need to use a file viewer (such as QuickLook) to view secure files in my iOS (Swift) application but I do not want to write the files to disk. I know Apple does disk encryption but that is not an option for us. Is there any way to use a file viewer (such as QuickLook) with a file that is purely in memory?
There's a way using URI scheme (data:MIME;base64):
(there's no safety in this code sample, force unwrap and such).
let data = //... get image data
let base64String = data!.base64EncodedString()
let imgURIPath = "data:application/octet-stream;base64,\(base64String)"
// More clear with format?
//let imgURIPath = String(format: "data:application/octet-stream;base64,%@", base64String)
// We need a dummy base URL since URL(string:) is validating the URL
// and will return nil if there's no valid base
let baseURL = URL(string: "https://www.dummyURL.com")!
let uri = URL(string: imgURIPath, relativeTo: baseURL)!
// Test
let imageFromURI = try? UIImage(contentsOf: uri)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With