Home > Software design >  Saving large videos in iOS
Saving large videos in iOS

Time:08-11

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()
                }
            }
        }
    }

CodePudding user response:

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

CodePudding user response:

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)
}
  • Related