我目前正在我的应用程序中显示视频,希望用户能够将其保存到其设备图库/相册照片/相机胶卷中。这就是我正在做的事情,但视频未保存在相册中:/
func downloadVideo(videoImageUrl:String) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { //All stuff here print("downloadVideo"); let url=NSURL(string: videoImageUrl); let urlData=NSData(contentsOfURL: url!); if((urlData) != nil) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]; let fileName = videoImageUrl; //.stringByDeletingPathExtension let filePath="\(documentsPath)/\(fileName)"; //saving is done on main thread dispatch_async(dispatch_get_main_queue(), { () -> Void in urlData?.writeToFile(filePath, atomically: true); print("videoSaved"); }) } }) }
我也调查这个:
let url:NSURL = NSURL(string: fileURL)!; PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(url); let assetPlaceHolder = assetChangeRequest!.placeholderForCreatedAsset; let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection) albumChangeRequest!.addAssets([assetPlaceHolder!]) }, completionHandler: saveVideoCallBack)
但是我有错误“无法从文件创建数据(空)”。我的“ assetChangeRequest”为零。我不了解我的网址是有效的,并且当我使用浏览器访问它时,它会下载快速时间文件。
如果有人可以帮助我,将不胜感激!我正在使用Swift,并将iOS 8.0分钟作为目标。
更新资料
想要使用URLSession更新Swift 3的答案,并想知道答案已经存在于此处的相关主题中。用它。
原始答案
下面的代码将视频文件保存到Camera Roll。我对代码进行了细微的更改,将let fileName = videoImageUrl;其重用- 我将其删除,因为它会导致文件路径错误。
let fileName = videoImageUrl;
我测试了此代码,并将其保存到相机胶卷中。您询问了要放入的内容creationRequestForAssetFromVideoAtFileURL-放置一个指向下载的视频文件的链接,如下例所示。
creationRequestForAssetFromVideoAtFileURL
let videoImageUrl = "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4" DispatchQueue.global(qos: .background).async { if let url = URL(string: urlString), let urlData = NSData(contentsOf: url) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]; let filePath="\(documentsPath)/tempFile.mp4" DispatchQueue.main.async { urlData.write(toFile: filePath, atomically: true) PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath)) }) { completed, error in if completed { print("Video is saved!") } } } } }