App freezes / locks up when writing very large files

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?

Answers


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()

Need Your Help

Javascript Text Editor in UIWebView using execCommand

javascript colors uiwebview font-face

Why can't the following javascript command set the font color in RGB hex used in a UIWebView html rich text editor ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.