Swift - 使用downloadTaskWithURL下载视频

时间:2016-02-19 11:02:30

标签: ios iphone swift ipad nsurlsessiondownloadtask

我正在通过downloadTaskWithURL下载视频,并使用此代码将其保存到我的图库:

    func saveVideoBis(fileStringURL:String){

    print("saveVideoBis");

    let url = NSURL(string: fileStringURL);
    (NSURLSession.sharedSession().downloadTaskWithURL(url!) { (location:NSURL?, r:NSURLResponse?, e:NSError?) -> Void in

        let mgr = NSFileManager.defaultManager()

        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0];

        print(documentsPath);

        let destination = NSURL(string: NSString(format: "%@/%@", documentsPath, url!.lastPathComponent!) as String);

        print(destination);

        try? mgr.moveItemAtPath(location!.path!, toPath: destination!.path!)

        PHPhotoLibrary.requestAuthorization({ (a:PHAuthorizationStatus) -> Void in
            PHPhotoLibrary.sharedPhotoLibrary().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(destination!);
                }) { completed, error in
                    if completed {
                        print(error);
                        print("Video is saved!");
                        self.sendNotification();
                    }
            }
        })
    }).resume()
}

它在我的模拟器上完美运行,但在我的iPad上,即使出现print("Video is saved!");,视频也不会保存。 你知道为什么吗?

我的控制台中也出现了该消息

  

无法从文件(null)

创建数据

2 个答案:

答案 0 :(得分:27)

请通过以下代码检查评论:

Xcode 8•Swift 3

import UIKit
import Photos

class ViewController: UIViewController {

    func downloadVideoLinkAndCreateAsset(_ videoLink: String) {

        // use guard to make sure you have a valid url
        guard let videoURL = URL(string: videoLink) else { return }

        guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

        // check if the file already exist at the destination folder if you don't want to download it twice
        if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(videoURL.lastPathComponent).path) {

            // set up your download task
            URLSession.shared.downloadTask(with: videoURL) { (location, response, error) -> Void in

                // use guard to unwrap your optional url
                guard let location = location else { return }

                // create a deatination url with the server response suggested file name
                let destinationURL = documentsDirectoryURL.appendingPathComponent(response?.suggestedFilename ?? videoURL.lastPathComponent)

                do {

                    try FileManager.default.moveItem(at: location, to: destinationURL)

                    PHPhotoLibrary.requestAuthorization({ (authorizationStatus: PHAuthorizationStatus) -> Void in

                        // check if user authorized access photos for your app
                        if authorizationStatus == .authorized {
                            PHPhotoLibrary.shared().performChanges({
                                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)}) { completed, error in
                                    if completed {
                                        print("Video asset created")
                                    } else {
                                        print(error)
                                    }
                            }
                        }
                    })

                } catch { print(error) }

            }.resume()

        } else {
            print("File already exists at destination url")
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadVideoLinkAndCreateAsset("https://www.yourdomain.com/yourmovie.mp4")
    }

}

答案 1 :(得分:0)

如果您要从URL下载视频,但又不想将其存储在图库中。 以下代码对我有用...

 func createDownloadTask(videoURL: String,index: Int) {
    let downloadRequest = NSMutableURLRequest(url: URL(string: videoURL)!)
    let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
    self.downloadTask = session.downloadTask(with: downloadRequest as URLRequest, completionHandler: { (url, response, error) in
        print("asdasd")
        if error != nil{
            if super.reachability.connection == .none{
                self.showalert(msg: error?.localizedDescription ?? "")
            }else{
                self.downloadTask?.resume()
            }
        }

        guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
        // create a deatination url with the server response suggested file name
        let destinationURL = documentsDirectoryURL.appendingPathComponent(response?.suggestedFilename ?? "")

        do {
            if url != nil{
            try FileManager.default.moveItem(at: url!, to: destinationURL)
            }

            }

        } catch { print(error) }

    })
    self.downloadTask!.resume()
}