views:

219

answers:

1

Hi,

I have the following methods in my class:

-(IBAction)loginToAccount:(id)sender {
 // Display the network activity status indicator
 [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

 // Show the load indicator
 [self.loadIndicator startAnimating];
 self.loadIndicator.hidden = NO;
 self.loadLabel.hidden = NO;

 [usernameTextField resignFirstResponder];
 [passwordTextField resignFirstResponder];

 [self CheckLoginCredentials];
}

-(void)CheckLoginCredentials {
 NSString *APIURL = [[NSString alloc] initWithFormat:@"http://mysite.com/xml.xml"];
 NSURL *url = [[NSURL alloc] initWithString:APIURL];
 NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
 [APIURL release];
 [url release];

 [xmlParser setDelegate:self];
 [xmlParser parse];
}

When I comment [self CheckLoginCredentials], the loadIndicator gets animated and shown but when I uncomment [self CheckLoginCredentials], the loadIndicator does not get shown and also usernameTextField/passwordTextField resignFirstResponder do no work.

What am I doing wrong? Thanks!

+2  A: 

I believe that -initWithContentsOfURL: is a synchronous url connection, and therefore blocks the thread it's run on until it completes.

Because of this, the progress indicator won't get shown because it requires that the thread it's running on has an active run loop. Using the synchronous url connection on the main thread will block the UI on that thread, so you won't see your progress indicator.

The correct way to do this would be to use NSURLConnection's

+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate

Simply create an NSURLRequest object that encapsulates your API request, and then pass it off to that method on NSURLConnection.

Then implement the delegate call backs to get your data back.

The advantage of this method is that all of this is done on a separate thread and handled for you, and therefore won't block your UI.

Jasarien
Thanks Jasarien, it worked!
TamTam