Swift:将视频从NSURL保存到用户相机胶卷

jv4diomz  于 2023-06-21  发布在  Swift
关注(0)|答案(7)|浏览(141)

我有一个NSURL类型的变量videoURL
如果我调用println(videoURL),它将返回如下内容:http://files.parsetfss.com/d540f71f-video.mp4
我有一个按钮设置,应该采取这个videoURL和保存视频到用户的相机胶卷。
我做过的最好的事情是这样的:

UISaveVideoAtPathToSavedPhotosAlbum(videoPath: String!, completionTarget: AnyObject!, completionSelector: Selector, contextInfo: UnsafeMutablePointer<Void>)

虽然我甚至不确定这是否有效,但我不知道如何将videoFile:NSURL转换为videoPath
任何帮助都是赞赏这一点。

    • 编辑:**

以下操作不成功:

UISaveVideoAtPathToSavedPhotosAlbum(videoURL.relativePath, self, nil, nil)
e4yzc0pl

e4yzc0pl1#

AssetsLibrary已弃用
1:导入照片

import Photos

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

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

7cwmlq892#

接受的答案不再适用于Swift 3.0和iOS 10。
首先,您需要在应用的plist文件中设置以下权限:
隐私-照片库使用说明
提供一个字符串,向用户解释请求权限的原因。
接下来,导入照片:

import Photos

最后是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)
    }
}
vddsk6oq

vddsk6oq3#

将视频从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)
}

参考来源:https://www.raywenderlich.com/94404/play-record-merge-videos-ios-swift

insrf1ej

insrf1ej4#

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

功能使用

self.saveVideoToAlbum(/* pass your final url to save */) { (error) in
                        //Do what you want 
                    }
  • 不要忘记导入照片并将隐私-照片库使用说明添加到您的info.plist*
kx1ctssn

kx1ctssn5#

自iOS 9起已弃用

1:导入资产库

import AssetsLibrary

2:使用此代码将视频从url保存到相机库。

ALAssetsLibrary().writeVideoAtPathToSavedPhotosAlbum(outputFileURL, completionBlock: nil)
mrphzbgm

mrphzbgm6#

只需使用它并粘贴视频的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
        }
}
fv2wmkja

fv2wmkja7#

使用await/async和Swift 5的现代版本。

import Foundation
import Photos

class PhotoLibrary {

    class func requestAuthorizationIfNeeded() async -> PHAuthorizationStatus {
        let status = PHPhotoLibrary.authorizationStatus(for: .readWrite)

        if status == .notDetermined {
            return await PHPhotoLibrary.requestAuthorization(for: .readWrite)
        } else {
            return status
        }
    }

    enum PhotoLibraryError: Error {
        case insufficientPermissions
        case savingFailed
    }

    class func saveVideoToCameraRoll(url: URL) async throws {

        let authStatus = await requestAuthorizationIfNeeded()

        guard authStatus == .authorized else {
            throw PhotoLibraryError.insufficientPermissions
        }

        do {
            try await PHPhotoLibrary.shared().performChanges {
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
            }
        } catch {
            throw PhotoLibraryError.savingFailed
        }
    }
}

然后这样使用:

do {
    try await PhotoLibrary.saveVideoToCameraRoll(url: url)
} catch {
    // Handle error
}

相关问题