Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Created April 15, 2020 01:11
Show Gist options
  • Save alexpaul/18ba51dd328ed826500506c3365fe176 to your computer and use it in GitHub Desktop.
Save alexpaul/18ba51dd328ed826500506c3365fe176 to your computer and use it in GitHub Desktop.
Convert persisted Data to a temporary URL to configure an AVPlayer for video playback.
import AVFoundation
extension Data {
func convertToURL() -> URL {
let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("video").appendingPathExtension("mp4")
do {
try self.write(to: tempURL, options: [.atomic])
} catch {
print()
}
return tempURL
}
}
let videoData = Data() // video data from persistence (can be Core Data, Documents Directory, Firebase.....)
// AVPlayer(url: url) needs a URL from a local source to playback video
let url = videoData.convertToURL()
// Now we can create an instance of AVPlayer with the converted URL
let player = AVPlayer(url: url)
// The file system will periodically remove temporary files as needed but we can be proactive and remove the file before hand
do {
try FileManager.default.removeItem(at: url)
} catch {
print("failed to remove temporary url with error: \(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment