0

I'm downloading and writing ~200mb podcasts into the Documents directory with the following code:

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")
    }
}

})

The sendAsynchronousRequest call prevents the lockup from happening during the download, but the app still freezes when it starts actually writing it to the directory.

Is there a way to prevent the lockup from happening at all, or am I going to have to write smaller chunks at a time?

allocate
  • 1,323
  • 3
  • 14
  • 28

1 Answers1

1

You won't be able to store 200MB in memory before trying to write it to disk, but you can use downloadTaskWithURL method, it writes the file to a temporary folder and you can move it when it finishes to the documents folder as follow.

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()
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571