开发者

Add NSURLConnection loading process on UIProgressView

I created a UIProgressView. But i used NSTimer to UIProgressView's process . Now I need to integr开发者_如何学JAVAate UIProgressView process, when URL is loading. UIProgressView's size will be depends upon the NSURLConnection's data.

I used the following code to NSURLConnection.

-(void)load {
    NSURL *myURL = [NSURL URLWithString:@"http://feeds.epicurious.com/newrecipes"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:60];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    responseData = [[NSMutableData alloc] init];
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [connection release];

    UIAlertView *alert = [[UIAlertView alloc] init];
    [alert setTitle:@"Warning"];
    [alert setMessage:@"Network Connection Failed?"];
    [alert setDelegate:self];
    [alert addButtonWithTitle:@"Yes"];

    [alert show];
    [alert release];

    NSLog(@"Error");
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    responsetext = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}


In your didReceiveResponse function you could get the total filesize like so: _totalFileSize = response.expectedContentLength;.

In your didReceiveData function you can then add up to a total bytes received counter: _receivedDataBytes += [data length];

Now in order to set the progressbar to the correct size you can simply do: MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize

(either in the didReceiveData function or somewhere else in your code)

Don't forget to add the variables that hold the number of bytes to your class!

I hope this helps..

EDIT: Here's how you could implement the delegates in order to update progressview

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    _totalFileSize = response.expectedContentLength;
    responseData = [[NSMutableData alloc] init];
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
   _receivedDataBytes += [data length];
   MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize;
   [responseData appendData:data];
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜