ios Swift:将视频从 NSURL 保存到用户相机胶卷
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29482738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: save video from NSURL to user camera roll
提问by George Poulos
I have a variable videoURL
of type NSURL.
我有一个videoURL
NSURL 类型的变量。
If I call println(videoURL)
it would return something like this:
http://files.parsetfss.com/d540f71f-video.mp4
如果我调用println(videoURL)
它会返回如下内容:
http://files.parsetfss.com/d540f71f-video.mp4
I have a button set up that should take this videoURL and save the video to the user's camera roll.
我有一个按钮设置,应该使用这个 videoURL 并将视频保存到用户的相机胶卷。
The best I have done is this:
我做过的最好的事情是这样的:
UISaveVideoAtPathToSavedPhotosAlbum(videoPath: String!, completionTarget: AnyObject!, completionSelector: Selector, contextInfo: UnsafeMutablePointer<Void>)
While I'm not even sure if this will work or not, I can't figure out how to convert videoFile:NSURL
into a videoPath
.
虽然我什至不确定这是否可行,但我不知道如何转换videoFile:NSURL
为videoPath
.
Any help is appreciated on this.
对此的任何帮助表示赞赏。
Edit:
编辑:
The following is unsuccessful:
以下是不成功的:
UISaveVideoAtPathToSavedPhotosAlbum(videoURL.relativePath, self, nil, nil)
回答by Boris
AssetsLibrary is deprecated
AssetsLibrary 已弃用
1: import Photos
1:导入照片
import Photos
2: Use this code to save video from url to camera library.
2:使用此代码将视频从 url 保存到相机库。
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(nsUrlToYourVideo)
}) { saved, error in
if saved {
let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
Swift 3 & Swift 4
斯威夫特 3 和斯威夫特 4
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: urlToYourVideo)
}) { saved, error in
if saved {
let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
回答by CodeBender
The accepted answer no longer works with Swift 3.0 & iOS 10.
接受的答案不再适用于 Swift 3.0 和 iOS 10。
First, you need to set the following permission in your app's plist file:
首先,您需要在应用的 plist 文件中设置以下权限:
Privacy - Photo Library Usage Description
隐私 - 照片库使用说明
Provide a string that is presented to the user explaining why you are requesting the permission.
提供一个显示给用户的字符串,解释您请求权限的原因。
Next, import photos:
接下来,导入照片:
import Photos
Finally, here is the updated code for Swift 3.0:
最后,这里是Swift 3.0的更新代码:
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileURL)
}) { saved, error in
if saved {
let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
回答by Disha
To save video from NSURL to user camera roll
将视频从 NSURL 保存到用户相机胶卷
func video(videoPath: NSString, didFinishSavingWithError error: NSError?, contextInfo info: AnyObject)
{
if let _ = error {
print("Error,Video failed to save")
}else{
print("Successfully,Video was saved")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let conversationField = self.conversation {
if (mediaType?.isEqual((kUTTypeMovie as NSString) as String))!
{
let theVideoURL: URL? = (info[UIImagePickerControllerMediaURL] as? URL)
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum((theVideoURL?.path)!))
{
UISaveVideoAtPathToSavedPhotosAlbum((theVideoURL?.path)!, self, #selector(ConversationDetailsViewController.video(videoPath:didFinishSavingWithError:contextInfo:)), nil)
}
}
self.dismiss(animated: true, completion: nil)
}
Reference from:: https://www.raywenderlich.com/94404/play-record-merge-videos-ios-swift
参考自:https: //www.raywenderlich.com/94404/play-record-merge-videos-ios-swift
回答by Saqib Omer
deprecated as of iOS 9
自 iOS 9 起弃用
1: import AssetsLibrary
1:导入AssetsLibrary
import AssetsLibrary
2: Use this code to save video from url to camera library.
2:使用此代码将视频从 url 保存到相机库。
ALAssetsLibrary().writeVideoAtPathToSavedPhotosAlbum(outputFileURL, completionBlock: nil)
回答by Hacker Mane
Just use it and paste your video's url:
只需使用它并粘贴您的视频网址:
PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
let createAssetRequest: PHAssetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(NSURL(string: /* your url */)!)!
createAssetRequest.placeholderForCreatedAsset
}) { (success, error) -> Void in
if success {
//popup alert success
}
else {
//popup alert unsuccess
}
}
回答by Mithilesh Kuamr
Try this instead for saving video in photo library in swift 4.2 and above
试试这个,以在 swift 4.2 及更高版本的照片库中保存视频
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
}
Don't forgot to import Photos and add Privacy - Photo Library Usage Description to your info.plist
不要忘记导入照片并将隐私 - 照片库使用说明添加到您的 info.plist