2016-03-05 71 views
0

我需要從服務器下載視頻並保存視頻以備後用。Swift保存下載的視頻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() 
} 
+0

您可以使用響應suggestedFilename –

+0

'downloadTask.response?.suggestedFilename' –

+0

@LeoDabus確定它給我的文件名,現在我該怎樣保存和重新使用它 –

回答

0

那麼我改變了整個func並修復它。

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { 
    statusLabel.text = "Download finished" 

    print(downloadTask.response!.suggestedFilename!) 

    let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL 
    // your destination file url 
    let destinationUrl = documentsUrl.URLByAppendingPathComponent(String(downloadTask.response!.suggestedFilename!)) 
    print(destinationUrl) 

    if NSFileManager().fileExistsAtPath(destinationUrl.path!) { 
     print("The file already exists at path") 
    } else { 

     let data = NSData(contentsOfURL: (downloadTask.response!.URL)!) 

     if data!.writeToURL(destinationUrl, atomically: true) { 
      print("file saved") 
     } else { 
      print("error saving file") 
     } 

    } 



    let filePath = String(destinationUrl.path!) 
    var fileSize : UInt64 = 0 

    do { 
     let attr : NSDictionary? = try NSFileManager().attributesOfItemAtPath(filePath) 

     if let _attr = attr { 
      fileSize = _attr.fileSize(); 
      print(fileSize) 
      self.statusLabel.text = String(fileSize) 
      self.performSegueWithIdentifier("video", sender: self) 
     } 
    } catch { 
     print("Error: \(error)") 
    } 

    resetView() 
}