I have an app with in-app downloading. I successfully download mp3 files in this way:
NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://.../somefile.mp3"]];
[data1 writeToFile:filePath atomically:YES];
But there is really big pause while this code is executing. How can I work out the progress of the download and display it with a progress bar?
The problem is that dataWithContentsOfURL:
is a blocking call. This means that it will block the thread that it is running on.
You've got a couple of options to fix this, and the better one is probably to use an NSURLConnection
.
With an NSURLConnection
you can perform the download request asynchronously, which will prevent it from blocking the main thread.
You must use the NSURLConnectionDelegate
methods to be informed of the progress of the download, save its data, and to be informed of success or failure.
Please read the documentation for the NSURL Loading System.
An alternative to using NSURLConnection
is to wrap your current code with some calls to GCD using dispatch queues. This will prevent the call from blocking your UI, but it will not allow you to determine the progress - for that you will still need to use NSURLConnection
.
You should really have a look at the ASIHTTPRequest and especially this section
It provides callbacks for tracking your downloads, async and sync connections, queues, caching and lots of good stuff.