2

我是 Alamofire 框架的新手。我尝试下载数据文件。代码是:

Alamofire.download(.GET, urlStr, { (temporaryURL, response) in
            if let directoryURL = NSFileManager.defaultManager()
                .URLsForDirectory(.DocumentDirectory,
                    inDomains: .UserDomainMask)[0]
                as? NSURL {
                    let pathComponent = response.suggestedFilename

                    return directoryURL.URLByAppendingPathComponent(pathComponent!)
            }

            return temporaryURL
        })

文件下载成功。然而,所有进程都在使用内存。如您所见,问题是,如果我尝试下载大文件(我的意思是超过 50mb),我得到了 didReceiveMemoryWarning 并且应用程序自行关闭。我怎样才能防止这种情况?

在测试中,我尝试下载一部电影(大小为 220mb),在模拟器中,内存使用量高达 500mb。当我尝试我的手机时。它在显示内存警告后自行关闭。

4

1 回答 1

2

如果你想下载大文件,你可以考虑 thibaultCha 的另一个名为TCBlobDownloadSwift的库。它是 TCBlobDownload 的 Swift 版本,测试了从 ~150MB 到 ~1.2GB 的文件,主要是视频。

它的用法类似于 Alamofire:

import TCBlobDownloadSwift

// Here is a simple delegate implementing TCBlobDownloadDelegate.
class DownloadHandler: NSObject, TCBlobDownloadDelegate {
  init() {}

  func download(download: TCBlobDownload, didProgress progress: Float, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    println("\(progress*100)% downloaded")
  }

  func download(download: TCBlobDownload, didFinishWithError error: NSError?, atLocation location: NSURL?) {
    println("file downloaded at \(location)")
  }
}

let fileURL = NSURL(string: "http://some.huge/file.mp4")
let download = TCBlobDownloadManager.sharedInstance
                                    .downloadFileAtURL(fileURL!, toDirectory: nil, withName: nil, andDelegate: DownloadHandler())
于 2015-06-20T15:17:46.190 回答