如何使用URLSeassion

时间:2017-06-24 18:43:27

标签: ios swift swift3

我是swift的新手,我正在开发一个项目,用于下载内容并使用此代码将其保存到相机胶卷

    func downloadVideoLinkAndCreateAsset(_ videoURL: String) {
    // use guard to make sure you have a valid url
    guard let videoURL = URL(string: firstId) else { return }
    let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    // 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.removeItem(at: location)
                let urlData = NSData(contentsOf: videoURL)
                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
                let filePath="\(documentsPath)/template.mp4"
                urlData?.write(toFile: filePath, atomically: true)
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
                }) { completed, error in
                                if completed {
                                    print("Video asset created")

                                } else {
                                    print(error)
                        }
                    }
            } catch let error as NSError { print(error.localizedDescription)}

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

}

我目前有一个标签显示下载字节的百分比,还有一个进度视图来显示进度。 我找到了答案,我找到的大多数答案都是客观的C,你能帮忙吗?

你能否解释一下使用URLSession和下载内容之间的差异,以及是否可以实现标签和进度视图。

                DispatchQueue.global(qos: .background).async {
                if let url = URL(string: videoLink),
                    let urlData = NSData(contentsOf: url)
                {
                    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
                    let filePath="\(documentsPath)/template.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!")
                            }
                        }
                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

基于块/闭包的API不提供进度信息。

您需要使用基于协议/代理的API,采用NSURLSessionDownloadDelegate协议并实施方法urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)

optional func urlSession(_ session: URLSession, 
                      downloadTask: URLSessionDownloadTask, 
         didWriteData bytesWritten: Int64, 
                 totalBytesWritten: Int64, 
         totalBytesExpectedToWrite: Int64)