Search code examples
swifturlnsfilemanagerswift-playgroundphlivephoto

How to save a video to a URL in Swift Playgrounds


I'm trying to instantiate a PHLivePhoto but whenever I try to save the video that constitutes the live photo I can't get it to work.

Here's a little code snippet I wrote that handles exporting the video:

public func exportFilteredVideo(to outputURL: URL, completion: @escaping (Void) -> Void) {
    if FileManager.default.fileExists(atPath: outputURL.path) {
        try? FileManager.default.removeItem(at: outputURL)
    }

    let export = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality)!
    export.outputFileType = AVFileTypeQuickTimeMovie
    export.outputURL = outputURL
    export.videoComposition = generateComposition()
    export.exportAsynchronously(completionHandler: completion)
}

This is when I try to retrieve the video:

let destURL = url.deletingLastPathComponent().appendingPathComponent("Test.mov")
pixellationFilter.exportFilteredVideo(to: destURL) {
     print(try! destURL.checkResourceIsReachable()) //An error is thrown! Why though, isn't the export completed?
}

Currently, my suspicions are you might not be able to write to the URL specified. However, my understanding is that whenever I want to create a PHLivePhoto object I need to specify the resources as URL instead of Data. If this is possible, I would be able to instead use the data instead of exporting it to a URL. I could be wrong, but I'm not really finding a way to create a PHLivePhoto with Data. There is a PHAssetResource class but that only helps to get the data files of the PHLivePhoto not to create a PHLivePhoto.

So my possible solutions I believe at this moment are:

  1. Figure out how I can save the video as a URL.
  2. Try and create a live photo through Data instead of URL.

Solution

  • The fileURL it is just where the data is located. Just write the data to a temporary folder and pass that file url to the method.