Ajil O. Ajil O. - 1 month ago 23
iOS Question

Control flow during json parsing - Objective C

I am trying to create a login screen where one has to enter his UserName and Password. On clicking the login button I am parsing the details to the server. Here's the code

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",[_userNameText text],[_passwordText text]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu" , (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://*******/*****/******/userLogin.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"sample data"];
[request setHTTPBody:postData];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"%@",_requestReply);
}] resume];


So far the code works just as intended. Now I want to check if the "requestReply" that is returned from the server has the value "success" for it's "status" key. So I tried to print it's value with the following code.

_responseData = _requestReply;
NSLog(@"%@" , _responseData[@"status"]);


And here's the console output

2016-10-21 06:44:03.424 QuizApp2[65724:1287972] (null)
2016-10-21 06:44:03.501 QuizApp2[65724:1288003] {"status":"success","message":"Welcome admin","code":true}


I am not sure, but I felt that the last line of the code is executing before the parsing happens. Can someone please highlight how the control flows here? Or is there anything wrong with my code?

Answer

I didn't see any code about parse data. Do you mean this line

_requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

If the userLogin.php returns a JSON data, just do this:

[[session dataTaskWithRequest:request completionHandler:^(NSData *data , NSURLResponse *response , NSError *error){
    NSError *err = nil;
    id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
    if (err) {
        NSLog(@"%@", err);
    }
    else {
        NSLog(@"%@", jsonData[@"status"]);
    }
}] resume];