How to programmatically add a simple default loading(progress) bar in iphone app

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
indicator.center = self.view.center;    
[self.view addSubview:indicator];
[indicator bringSubviewToFront:self.view];
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;

Write below code when you want to show indicator

[indicator startAnimating];

write below code when you want to hide indicator

[indicator stopAnimating];

Translating @Hiren's answer to Swift

 var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
 indicator.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
 indicator.center = view.center
 self.view.addSubview(indicator)
 self.view.bringSubview(toFront: indicator)
 UIApplication.shared.isNetworkActivityIndicatorVisible = true

Show indicator

indicator.startAnimating()

Stop indicator

indicator.stopAnimating()

I'd recommend using NSURLConnection. The methods you would need are:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  [self.resourceData setLength:0];
  self.filesize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  [self.resourceData appendData:data];
  NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.resourceData length]];
  self.progressBar.progress = [resourceLength floatValue] / [self.filesize floatValue];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  self.progressBar.hidden = YES;
}

And the header file:

@property (nonatomic, retain) UIProgressView *progressBar;
@property (nonatomic, retain) NSMutableData *resourceData;
@property (nonatomic, retain) NSNumber *filesize;

Hope it helps

Tags:

Ios

Iphone