Loading progress bar

I have an in-app download app. I am successfully downloading mp3 files this way:

NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://.../somefile.mp3"]];
[data1 writeToFile:filePath atomically:YES];

      

But there is really a big pause when executing this code. How can I detect the progress of the download and display it with a progress bar?

+3


source to share


2 answers


The problem is what dataWithContentsOfURL:

is a blocking call. This means that it will block the thread it is running on.

You have several options to fix this, and your best bet is probably to use NSURLConnection

.

With help, NSURLConnection

you can execute the download request asynchronously, which will prevent the main thread from blocking.



You should use methods NSURLConnectionDelegate

to get information about the progress of a download, save its data, and get information about success or failure.

Please see the documentation for the NSURL download system .

An alternative usage NSURLConnection

is to port your current code to some GCD calls using send queues. This will prevent the call from blocking your UI, but it will prevent you from detecting progress - you still have to use NSURLConnection

.

+4


source


You should really take a look at ASIHTTPRequest and especially this section



It provides callbacks to keep track of your downloads, async and sync connections, queues, caching, and much more.

+1


source







All Articles