Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift create URL object from Data (byte array) without writing to disk

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?

like image 528
Alec Avatar asked Oct 28 '25 04:10

Alec


1 Answers

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)
like image 107
bauerMusic Avatar answered Oct 30 '25 19:10

bauerMusic