0

I am performing a download through NSURLConnection class and updating a progress bar view according to the received bytes in the NSURLConnection delegate connection didReceiveData.

Everything is working fine when I am on the page where downloading is happening but when I am going to some other view controller and coming back to my downloading page, the connection delegate functions are being called while transition of page but coming back does not upgrade the progress bar.

The code I am using is:

- (IBAction)download:(id)sender {
    _currentURL = [NSString stringWithFormat:@"url_to_download"];
    NSURL *url =[NSURL URLWithString:_currentURL];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];

    _receivedData = [[NSMutableData alloc]initWithLength:0];
    connection2 = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self startImmediately:YES];
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSLog(@"THE STATUS CODE IS %d",[httpResponse statusCode]);
    statuscode = [httpResponse statusCode];
    NSLog(@"into didReceiveResponse");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [_receivedData setLength:0];
    expectedBytes = [response expectedContentLength];
    NSLog(@"EXPECTED BYTES:%ld",expectedBytes);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"into did receivedata");
    [_receivedData appendData:data];

        self.setting.enabled = NO;
        float progressive = (float)[_receivedData length] / (float)expectedBytes;
        [self.progress setProgress:progressive];

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
   AppDelegate *app = (AppDelegate*) [[UIApplication sharedApplication]delegate];
    NSLog(@"into didfailwitherror");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"connection failed");


}

-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    return nil;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

        self.setting.enabled = YES;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSLog(@"DOCUMENT DIRECTORY :%@",documentsDirectory);

        _imagePath = [documentsDirectory stringByAppendingPathComponent:_fullPath];
        NSLog(@"iamge path:%@",_imagePath);
        NSLog(@"succeeded");
        [UIApplication sharedApplication].networkActivityIndicatorVisible= NO;
        NSLog(@"Succeeded! Received %d bytes of data",[_receivedData length]);

        // flag= [_receivedData writeToFile:imagePath atomically:NO];
        if([_receivedData writeToFile:_imagePath atomically:YES])
        {

            NSLog(@"write successfull");
            app.dl_status = 0;
            [HUD hide:YES];
            [HUD removeFromSuperview];
            HUD = nil;
            [self completedDownloadHUD];
            [self.download setBackgroundImage:[UIImage imageNamed:@"download.png"] forState:UIControlStateNormal];
        }
        else{
            app.dl_status = 0;
            NSLog(@"write failed");
            [HUD hide:YES];
            [self errorDownloadHUD];
        }

        NSString *imagePathExtension;
        imagePathExtension = [_imagePath pathExtension];
        if([imagePathExtension isEqual:@"jpg"])
        {
            NSLog(@"imagepathextension is jpg");
            UIImage *img =[UIImage imageWithContentsOfFile:_imagePath];
            UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

        }
        else if([imagePathExtension isEqual:@"mov"])
        {
            NSLog(@"imagepathextension is mp4");
            UISaveVideoAtPathToSavedPhotosAlbum(_imagePath, nil, nil, nil);
        }


}

Please tell me how i can retain the value of progress bar while coming back to page and update it.

David H
  • 40,852
  • 12
  • 92
  • 138
MeghaJain
  • 164
  • 1
  • 1
  • 8
  • As a new user you may not completely understand how this site works - if someone answers your question, and it helps you or solves a problem, then the original poster is suppose to select the answer by tapping on the check under the answer. Other people will avoid your questions if you ask many but never select answers. – David H Nov 25 '13 at 13:53

1 Answers1

0

Change your delegate to this then update the question. I suspect you will find something gets hit with the asserts:

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"into didReceiveData");
    [_receivedData appendData:data];
    assert(_receivedData); // it exists
    assert([_receivedData length]); // it also has some data in it 

    self.setting.enabled = NO;
    float progressive = (float)[_receivedData length] / (float)expectedBytes;
    assert(expectedBytes > 0);
    assert(progressive > 0 && progressive <= 1);
    assert(self.progress);
    assert(!self.progress.hidden);
    assert(!self.progress.alpha > 0.5);
    assert(self.progress.window);
    [self.progress setProgress:progressive];
}

If you don't get any asserts, you still are getting delegate messages, and the progress bar is not visible (or not moving) then log the value of progressive and/or the progress bar frame.

David H
  • 40,852
  • 12
  • 92
  • 138
  • yes..the problem was with the delegate.i made another delegate and then update happened. Thanks a lot for this help. – MeghaJain Nov 25 '13 at 07:02
  • Can you please update how did you fix this @MeghaJain ? What do you mean by made another delegate ? – AnxiousMan Jul 26 '17 at 09:13
  • @ManeeshSharma I believe what he means is that he had one VC as delegate, and when that was dismissed there was no delegate. So he "transferred" delegation to another VC. Generally I dislike this approach, would prefer to have a singleton handling all messages, then VCs can communicate with that to determine progress etc. That said many ways to deal with this issue. – David H Jul 26 '17 at 16:56
  • Thank you David ! And it is 'She' not 'He'. Moreover, My class is updated with the new class instance. But the NSURLSession delegate methods somehow don't get updated even if I call self. They persist the old class instance – AnxiousMan Jul 27 '17 at 06:56