Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progress bar while downloading

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?

like image 844
Eugene Trapeznikov Avatar asked Dec 05 '25 08:12

Eugene Trapeznikov


1 Answers

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.

like image 162
Jasarien Avatar answered Dec 07 '25 22:12

Jasarien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!