在编写非常大的文件时,应用程序冻结/锁定

时间:2015-05-05 21:49:20

标签: swift sendasynchronousrequest

我使用以下代码将〜200mb播客下载并写入Documents目录:

var podcastRequest = NSURLRequest(URL: audioUrl)
NSURLConnection.sendAsynchronousRequest(podcastRequest, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if let myPodcastDataFromUrl = NSData(contentsOfURL: audioUrl) {

    if myPodcastDataFromUrl.writeToURL(destinationUrl, atomically: true) {

        // add to the array to track the download
        var tempDic = self.posts[theRow] as! NSMutableDictionary as NSMutableDictionary
        tempDic["downloaded"] = "true"
        self.posts[theRow] = tempDic
    } else {
        println("Error saving file")
    }
}

})

sendAsynchronousRequest调用可以防止在下载过程中发生锁定,但是当应用程序开始实际将其写入目录时,应用程序仍会冻结。

有没有办法防止锁定发生,或者我是否必须一次编写较小的块?

1 个答案:

答案 0 :(得分:1)

在尝试将其写入磁盘之前,您将无法在内存中存储200MB,但是您可以使用downloadTaskWithURL方法,它将文件写入临时文件夹,并且可以在文档文件夹完成时将其移动到跟随。

let documentsDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL

NSURLSession.sharedSession().downloadTaskWithURL(audioUrl, completionHandler: {
    (location, response, error) -> Void in

    if let error = error {
        println(error.description)
    }
    else {
        if NSFileManager().moveItemAtURL(location, toURL: documentsDirectoryURL.URLByAppendingPathComponent(response.suggestedFilename!), error: nil) {
            println("saved")
        } else {
            println("not saved.")
        }
    }
}).resume()