Search code examples
swiftiphonexcodevideoimglykit

How to save a video from my app in to the users photo library in iOS?


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?


Solution

  • 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.