pierceography
pierceography

Reputation: 93

View Controller Segue Delay after NSURLConnection

So this is my first post, I've found this site incredibly informative in my brief history with Objective C and iOS programming. Anyhow, I've run into a problem of sorts. A quick summary: I'm attempting to write a login form, which uses calls a custom class that with hit a webserver to auth using NSURLConnection. I'm using protocols and delegates to delegate back to the calling class to perform a segue to the main menu view controller once the authentication is complete.

The problem is that the menu I'm attempting to segue into takes anywhere from 6 to 75 seconds to display. If I remove the API call, it loads immediately. However, I'm doing logging throughout the process, and everything appears to step through at a normal pace. I even log when the menu view controller is loaded, and all logging happens normally. But the actual display of the menu is delayed!

Here are some code details:

View Controller Methods:

- (void) userLogin:(NSString *)userName password:(NSString *)password {
    NSLog(@"VC login method");
    api = [theAPI getSelf];
    [api setDelegate:self];
    [api userLogin:userName password:password];
}

- (void) userLoginDone:(BOOL)successful {
    [self performSegueWithIdentifier:@"sgLoginToMainMenu" sender:self];
    NSLog(@"Login Done");
}

API Method:

- (void) userLogin:(NSString *)userName password:(NSString *)password {
    NSURL *url = [NSURL URLWithString:(NSString *) [API_PATH stringByAppendingString:@"test.html"]];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        NSDictionary *json = [[JSON new] parseJSON:data];

        self.usrID = [json objectForKey:@"usrID"];
        self.sessionID = [json objectForKey:@"sessionID"];
        self.userName = [json objectForKey:@"Username"];

        NSLog(@"Username: %@", [json objectForKey:@"Username"]);

        [[self delegate] userLoginDone:YES];
    }];
}

All the NSLogs execute in a normal timespan (few milliseconds). Yet the main menu view controller takes entirely too long to appear! I'm very new to iOS programming, so I'm hoping I'm just overlooking something that googling couldn't solve. Any help would be greatly appreciated!

Upvotes: 2

Views: 932

Answers (1)

Peter E
Peter E

Reputation: 4931

You need to update the UI on the main thread, but userLoginDone: is being called on an NSOperationQueue, which create its own separate thread. This could explain the delay in displaying. Have you tried using [NSOperationQueue mainQueue] (which returns the queue associated with the main thread) to pass to sendAsynchronousRequest: instead?

Upvotes: 4

Related Questions