Thursday, 22 September 2016

Show download progress of the content

In iOS when we download any content , there may be a need to show the progress of the download. It's easy in iOS. We can download the data with NSURLConnection. 

First of all create a UIProgressBar in your view and initially make it hidden. Lets say we have a progress bar outlet named  progressBar .


1) Create NSURLConnection object

NSURL *url = [NSURL URLWithString:@"Your_url"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:80];

   NSMutableData *dataReceived = [[NSMutableData alloc] initWithLength:0];
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];


2) Now implement the delegate methods of the NSURLConnection

 In this method we receive the response of the download, from which we get the expected content length.Also we make the progress bar unhidden here.

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
     self.progressBar.hidden = NO;
    [dataReceived setLength:0];
    long long  expectedDataBytes = [response expectedContentLength];
}


In didReceiveData:(NSData*)data method we get the downloaded data chunks, here we append the data to dataReceived object . And also set the progress bar by download progress .

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [dataReceived appendData:data];
    float downloadProgress = (float)[dataReceived length] / (float) expectedDataBytes;
     [self.progressBar setProgress: downloadProgress];
    
}

When downloading is complete the connectionDidFinishLoading:(NSURLConnection*)connection method is called. Here we can save the downloaded content to the document directory.

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
   
}
    
Here I make the expectedDataBytes and dataReceived object local .You have to declare them to interface section of the file to use them in all methods.

Reference:

No comments:

Post a Comment