sapir1126
sapir1126

Reputation: 39

Saving large videos in iOS

I am trying to save a large video locally to the photo library using PHPhotoLibrary but i notice that it takes a very long time is there any way to get progress or even better to make the process faster

my code:

    func saveToLibrary(videoURL: URL, complition: @escaping () -> Void) {
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else { return }
            
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
            }) { success, error in
                if !success {
                    print("Could not save video to photo library: \( error as Any)")
                } else {
                    complition()
                }
            }
        }
    }

Upvotes: 0

Views: 277

Answers (2)

Christos Koninis
Christos Koninis

Reputation: 1688

You can first download the video in a temporary local file using NSURLSessionDownloadTask, and then pass the the URL from the that local file to PHPhotoLibrary. This way you can monitor the download progress.

Something like this would work:

 // Download the remote URL to a file
    let task = URLSession.shared.downloadTask(with: url) {
        (tempURL, response, error) in
        // Early exit on error
        guard let tempURL = tempURL else {
            return
        }

        // The file is downloaded in the tempURL we can save it in the library
        saveToLibrary(videoURL: tempURL, complition: {}) 
    }

    // Start the download
    task.resume()

    // Monitor the progress
    let observation = task.progress.observe(\.fractionCompleted) { progress, _ in
  print(progress.fractionCompleted)
}

Upvotes: 0

Jon_the_developer
Jon_the_developer

Reputation: 338

Do this on a background thread so that your UI doesn't get locked up.

Upvotes: 0

Related Questions