【问题标题】:Swift: save video from NSURL to user camera rollSwift:将视频从 NSURL 保存到用户相机胶卷
【发布时间】:2015-06-11 12:39:32
【问题描述】:

我有一个 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)

【问题讨论】:

  • 那是一个远程 URL。你无法保存它,因为你没有它。您将必须首先下载该文件。下载后,使用下载 URL(磁盘上文件的 URL)并将 那个保存到相机胶卷。所有这些都将非常耗时,因此您必须在后台线程中完成。
  • 虽然我只尝试了 30 分钟,但将远程 NSURL 转换为本地文件非常困难。如果您知道执行此操作的最佳方法或有任何链接,请告诉我。我正在尝试 NSURLConnection ,这很令人困惑。
  • 现在 NSURLSession 更容易了。并且使用下载任务是微不足道的。下面是一个例子:github.com/mattneub/Programming-iOS-Book-Examples/blob/master/… 在那个例子中,我下载了一张图片,然后把它放到了界面中。您将下载视频,然后将其保存到相机胶卷中。基本上是一样的想法!

标签: ios swift parse-platform save nsurl


【解决方案1】:

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

斯威夫特 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)
    }
}

【讨论】:

  • 您好,您知道是否可以获取相机胶卷中视频的Url 吗?我尝试与 FBSDKShareVideoContent 共享它,但我无法确定相机胶卷中的 URL(因为 FBSDKShareVideoContent 需要存储在相机胶卷中的视频)。
  • 哇,Swift 3 的解决方案看起来很眼熟!
  • 是的,添加 Swift 3 的人使用了你的,或者你们都从同一个地方拿走了它 =)
  • 这仅适用于本地网址吗?因为它不保存远程Url
【解决方案2】:

已接受的答案不再适用于 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)
    }
}

【讨论】:

  • CodeBender,这也适用于远程 URL 吗?或者我需要先下载它然后使用本地网址?
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    在 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

    【讨论】:

    • 赞成包含 requestAuthorization 方法!
    • 操作无法完成。 (PHPhotosErrorDomain 错误 -1。)“显示错误”
    【解决方案5】:

    自 iOS 9 起已弃用

    1:导入 AssetsLibrary

    import AssetsLibrary
    

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

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

    【讨论】:

    • 当心!自 iOS 9 起,AssetsLibrary 已被弃用
    【解决方案6】:

    只需使用它并粘贴您的视频网址:

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

    【讨论】:

      猜你喜欢
      • 2016-05-01
      • 2015-01-06
      • 1970-01-01
      • 2015-05-12
      • 2014-02-02
      • 1970-01-01
      • 2015-09-25
      • 2013-03-21
      • 1970-01-01
      相关资源
      最近更新 更多