简体   繁体   English

如何将我的应用程序中的视频保存到 iOS 中的用户照片库中?

[英]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.我的 iOS 应用程序允许用户拍照或录制视频,如果他们愿意,可以将其发送并保存到他们的相册中。 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).我已经尝试了以下代码,但 Xcode 给了我错误,例如“在范围中找不到‘UTTypeCopyPreferredTagWithClass’”等(我已经导入了 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?这段代码可以改进吗,或者有什么更好的方法可以用来将视频保存到 iOS 的照片库?

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 
                }

You can save the video to the gallery using UISaveVideoAtPathToSavePhotosAlbum您可以使用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.在 VideoPath 中,插入要保存的视频的路径。

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.另外可以先用函数UIVideoAtPathCompatibleWithSavedPhotosAlbum(_:)检查未保存的错误,看看视频是否可以存入图库。

For more information, see the apple developer site .有关更多信息,请参阅苹果开发者网站

Both of the provided answers are good.提供的两个答案都很好。 I picked Hailey's as the 'correct' one because it will be good for simply saving videos.我选择 Hailey's 作为“正确”的,因为它非常适合简单地保存视频。 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. Schaheer 的代码处理请求许可和保存视频,如果您有路径,Hailey 的代码只会保存视频。 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.对于使用 IMGLY 照片或视频编辑器 SDK 的其他人,我将很快发布我使用的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM