skip to Main Content

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

2

Answers


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

    Login or Signup to reply.
  2. 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)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search