How to stop UIActivityIndicatorView when uitextview loads current location using google api.
here is my code:
@implementation ViewController
@synthesize loctxt;
- (void)viewDidLoad {
loctxt=[[UITextView alloc]initWithFrame:CGRectMake(10, 50, 220, 30)];
loctxt.backgroundColor=[UIColor whiteColor];
loctxt.delegate=self;
[self.view addSubview:loctxt];
locbtn=[[UIButton alloc]initWithFrame:CGRectMake(240, 50, 40, 30)];
[locbtn addTarget:self action:@selector(clickToGetLocation)forControlEvents:UIControlEventTouchUpInside];
locbtn.backgroundColor=[UIColor grayColor];
[locbtn setImage:[UIImage imageNamed:@"sst14.gif"] forState:UIControlStateNormal];
[self.view addSubview:locbtn];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)clickToGetLocation {
spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,100, 20, 20)];
[spinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:spinner];
**[spinner startAnimating];**
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv",delegate.latitude, delegate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSLog(@"%@",locationString);
locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
**self.loctxt.text=[locationString substringFromIndex:6];**
//if i use code [spinner stopanimating]; here then the indicator does not appear
}
The problem is that you attempt to start the spinner, load data from the Internet, and then stop the spinner all on the main thread and all within the same method. Doing synchronous networking on the main thread is BAD.
You need to start the spinner, then perform the network access in the background. When this is complete, you then stop the spinner on the main thread.
GCD is very good for this. Something like this: