skip to Main Content

My iOS app allows the user to take a photo or record a video, send it and save it to their photo album if they wish. I’ve gotten everything done but I cannot figure out how to save the video. I’ve googled it, but most of the code I’ve seen seems to be outdated. I’ve tried the following code but Xcode gives me errors such as "’UTTypeCopyPreferredTagWithClass’ cannot be found in the scope" etc (I’ve imported UniformTypeIdentifiers). I am also not quite sure if this code actually does anything anyway.

// Write video to disk

guard let fileExtension = UTTypeCopyPreferredTagWithClass(photoEditViewController.configuration.photoEditViewControllerOptions.outputImageFileFormatUTI, kUTTagClassFilenameExtension)?.takeRetainedValue() as String?,
      let filename = (ProcessInfo.processInfo.globallyUniqueString as NSString).appendingPathExtension(fileExtension) else {
  return
}
let fileURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent(filename))
try? data.write(to: fileURL, options: [.atomic])

PHPhotoLibrary.shared().performChanges({
  PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: fileURL)
}) { _, _ in
  // Delete video from disk
  _ = try? FileManager.default.removeItem(at: fileURL)
}

Can this code be improved, or is there anything better to use to save videos to photo library for iOS?

3

Answers


  1. Chosen as BEST ANSWER

    Both of the provided answers are good. I picked Hailey's as the 'correct' one because it will be good for simply saving videos. For anyone who comes across this post in the future. You can use either depending on your needs. Schaheer's code handles both requesting permission and saving video and Hailey's code simply saves the video if you have the path. I sort of combined both of the above answers and used it with sample code provided from another source.

    For anyone else using the IMGLY photo or video editor SDK, I will post the code that I used shortly.


  2. Try using this to save video in photo library, refer Save video to camera roll

    func requestAuthorization(completion: @escaping ()->Void) {
        if PHPhotoLibrary.authorizationStatus() == .notDetermined {
            PHPhotoLibrary.requestAuthorization { (status) in
                DispatchQueue.main.async {
                    completion()
                }
            }
        } else if PHPhotoLibrary.authorizationStatus() == .authorized{
            completion()
        }
    }
    
    func saveVideoToAlbum(_ outputURL: URL, _ completion: ((Error?) -> Void)?) {
        requestAuthorization {
            PHPhotoLibrary.shared().performChanges({
                let request = PHAssetCreationRequest.forAsset()
                request.addResource(with: .video, fileURL: outputURL, options: nil)
            }) { (result, error) in
                DispatchQueue.main.async {
                    if let error = error {
                        print(error.localizedDescription)
                    } else {
                        print("Saved successfully")
                    }
                    completion?(error)
                }
            }
        }
    }
    

    Use of function:

    self.saveVideoToAlbum(/* pass your final url to save */) { (error) in
                        //Do what you want 
                    }
    
    Login or Signup to reply.
  3. You can save the video to the gallery using UISaveVideoAtPathToSavePhotosAlbum
    This function adds videos to the user’s camera roll album in the specified path.

    func UISaveVideoAtPathToSavedPhotosAlbum(_ videoPath: String, 
                                           _ completionTarget: Any?, 
                                           _ completionSelector: Selector?, 
                                           _ contextInfo: UnsafeMutableRawPointer?)
    

    In VideoPath, insert the path of the video you want to save.

    In addition, you can first use the function UIVideoAtPathCompatibleWithSavedPhotosAlbum(_:) to check for unsaved errors to see if the video can be stored in the gallery.

    For more information, see the apple developer site.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search