2015-07-11 74 views
0

我使用此代碼下載的MP4文件:如何在Swift中直接下載mp4到我的硬盤?

func downloadImageFile() { 
    let myURLstring = getImageURLCM() 
    let myFilePathString = "/Users/jack/Desktop/Comics/"+getTitle()+".mp4" 

    let url = NSURL(string: myURLstring) 
    let dataFromURL = NSData(contentsOfURL: url!) 

    let fileManager = NSFileManager.defaultManager() 
    fileManager.createFileAtPath(myFilePathString, contents: dataFromURL, attributes: nil) 
} 

但我注意到該文件實際上被加載上我RAM第一,NSFileManager其保存到我的硬盤驅動器之前(基於Xcode調試會話)。對於較小的文件,這是可以忍受的,但是我想下載的大部分文件至少是1GB

我的主要問題是:如何使這個RAM更友好?

我也注意到,我得到了死亡的紡車,直到下載完成,所以如果有關於修復的建議,我們將不勝感激。

回答

2

你最好在NSURLSession中使用系統託管下載,尤其是NSURLDownloadTask。這樣你就不必擔心大量下載的內存管理。在github上

import UIKit 
import XCPlayground 

func downloadFile(filePath: String) { 

    let url = NSURL(string: filePath) 

    if let unwrappedURL = url { 

     let downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(unwrappedURL) { (urlToCompletedFile, reponse, error) -> Void in 

      // unwrap error if present 
      if let unwrappedError = error { 
       print(unwrappedError) 
      } 
      else { 

       if let unwrappedURLToCachedCompletedFile = urlToCompletedFile { 

        print(unwrappedURLToCachedCompletedFile) 

        // Copy this file to your destinationURL with 
        //NSFileManager.defaultManager().copyItemAtURL 
       } 
      } 
     } 
     downloadTask?.resume() 
    } 
} 

downloadFile("http://devstreaming.apple.com/videos/wwdc/2015/711y6zlz0ll/711/711_networking_with_nsurlsession.pdf?dl=1") 

XCPSetExecutionShouldContinueIndefinitely() 

簡單的例子在這裏 - https://github.com/serendipityapps/NSURLSessionDownloadTaskExample

+0

我不能得到這個工作: - 從NSURLSession迅速文件

 /* * download task convenience methods. When a download successfully * completes, the NSURL will point to a file that must be read or * copied during the invocation of the completion routine. The file * will be removed automatically. */ func downloadTaskWithURL(url: NSURL, completionHandler: (NSURL?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDownloadTask? 

使用範例下面複製並粘貼到新雨燕遊樂場。運行時我無法看到網絡上發生的任何事情。 –

+0

我已將代碼示例更改爲我剛剛驗證的swift操場示例絕對可行 –

+0

完美無缺!現在我試圖用這行來複制文件,但是文件沒有被複制:'NSFileManager.defaultManager()。copyItemAtURL(unwrappedURLToCachedCompletedFile,toURL:destinationURL!,error:nil)'有什麼想法? –

1
dataFromURL.writeToFile(myFilePathString, atomically: true) 

這是我使用的代碼片段,它將加載的數據寫入給定路徑的文件中。

相關問題