0
Мне нужно скачать видео с сервера и сохранить видео для просмотра позже.Быстрое сохранение загруженного видео NSURLSession
Так что мне нужно скачать видео и сохранить его в файловой системе приложения с пользовательским именем, пока я могу загрузить данные (я думаю), но не могу их сохранить.
И нет, я не хочу использовать дополнительные рамки extinsions или что-то еще.
@IBOutlet var progressView: ProgressView!
@IBOutlet var statusLabel: UILabel!
@IBOutlet var downloadButton: DownloadButton!
private var downloadTask: NSURLSessionDownloadTask?
@IBAction func downloadButtonPressed() {
if let downloadTask = downloadTask {
downloadTask.cancel()
statusLabel.text = ""
} else {
statusLabel.text = "Downloading video"
downloadButton.setTitle("Stop download", forState: .Normal)
createDownloadTask()
}
}
func createDownloadTask() {
//small mp4 video link : http://techslides.com/demos/sample-videos/small.mp4
let url = NSURL(string: "http://techslides.com/demos/sample-videos/small.mp4")!
let downloadRequest = NSMutableURLRequest(URL: url)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
downloadTask = session.downloadTaskWithRequest(downloadRequest)
downloadTask!.resume()
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
progressView.animateProgressViewToProgress(progress)
progressView.updateProgressViewLabelWithProgress(progress * 100)
progressView.updateProgressViewWith(Float(totalBytesWritten), totalFileSize: Float(totalBytesExpectedToWrite))
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
statusLabel.text = "Download finished"
print(downloadTask.response.suggestedFilename) // Gives file name
resetView()
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil {
statusLabel.text = "Download failed"
} else {
statusLabel.text = "Download finished"
}
resetView()
}
func resetView() {
downloadButton.setTitle("Start download", forState: .Normal)
downloadTask!.cancel()
}
Вы можете использовать ответ suggestedFilename –
'downloadTask.response? .suggestedFilename' –
@LeoDabus ОК это дает мне имя файла как теперь я хранить и повторно использовать его –