is there any way to add activity indicator to wait upto data fetched completeley from nsurlconnection

326 Views Asked by At

I have a Login page in that when i press "login" button i have to call a webservice and load new view according to the response it is taking 3 to 4 seconds i want to show activity indicator for loading view

how to show that

i'm using asynchronous NSURLConnection with NSURLConnection delegates

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];

in didFinishLoading

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSError *e = nil;
res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&e];

//[indicator performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:YES];

NSLog(@"data is %@",res);
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"create.json"];

NSLog(@"file path is %@ ",path);

NSFileManager *fileManager=[NSFileManager defaultManager];

if(![fileManager fileExistsAtPath:path])
{

    NSString *bundle = [[[NSBundle mainBundle]resourcePath]stringByAppendingString:@"create.json"];

    [fileManager copyItemAtPath:bundle toPath:path error:&error];
}


[res writeToFile:path atomically:YES];

how to show in this view

i stucked here

1

There are 1 best solutions below

0
On

In your @interface, add:

@property (nonatomic, strong) UIActivityIndicatorView *ai;

When you start your connection, start your spinner:

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
_ai = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
_ai.frame = CGRectMake(0, 0, 24, 24); // adjust the frame to where you want the spinner to appear
[_ai startAnimating];
[self.view addSubview:_ai];

And when your connection completes, remove it:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [_ai stopAnimating];
    [_ai removeFromSuperView];

    ... // all your other code
}

Make sure you remove it the same way in the connectionDidFailWithError: callback as well. If you want something prettier, check out the github link @evnaz posted and use that instead of UIActivityIndicatorView with this same flow