Swift - 从远程URL下载视频并将其保存在相册中

问题描述 投票:14回答:3

我目前正在我的应用中显示视频,我希望用户能够将其保存到其设备库/专辑照片/相机胶卷。这是我正在做的,但视频没有保存在相册中:/

    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)

但我有错误“无法从文件创建数据(null)”。我的“assetChangeRequest”是零。我不明白,因为我的网址是有效的,当我使用浏览器访问它时,它会下载一个快速时间文件。

如果有人可以帮助我,我们将不胜感激!我正在使用Swift并定位iOS 8.0分钟。

ios iphone swift ipad
3个回答
24
投票

更新

想要使用URLSession更新Swift 3的答案,并想出答案已存在于相关主题here中。用它。

原始答案

下面的代码将视频文件保存到相机胶卷。我重复使用您的代码 - 我删除了let fileName = videoImageUrl;,因为它导致不正确的文件路径。

我测试了这段代码并将资产保存到相机胶卷中。您询问了如何放入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!")
                }
            }
        }
    }
}

11
投票

来自@Nimble的Swift 3版代码:

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

0
投票
PHPhotoLibrary.shared().performChanges({
     PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: video.url!)}) {
     saved, error in
     if saved {
          print("Save status SUCCESS")
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.