2015-07-11 62 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) 

这是我使用的代码片段,它将加载的数据写入给定路径的文件中。