Handle 401 status code with sendAsynchronousRequest:request API in iOS

◇◆丶佛笑我妖孽 提交于 2019-12-12 03:14:44

问题


I am using this way API to login in my app.

NSString *url = [NSString stringWithFormat:@"%@//login",xyz];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];


    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    if (!jsonData) {
        NSLog(@"Error creating JSON object: %@", [error localizedDescription]);
    }


    [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:APIKEY forHTTPHeaderField:@"X_API_KEY"];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:jsonData];

    [NSURLConnection sendAsynchronousRequest:request
     // the NSOperationQueue upon which the handler block will be dispatched:
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

         NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData: data options: 0 error: &error];  //I am using sbjson to parse

         if(httpResponse.statusCode == 200)
         {

             //Show message to user success
         }
         else  if(httpResponse.statusCode == 401)
         {
            //Show message to user -fail
         }
         else if(httpResponse.statusCode == 500)
         {
             //Show message to user- server error
         }
     }];

When I use correct user name and password, I get httpResponse and status code as 200. But if use wrong user name and password, I am not getting 401.

So how to handle this situation

Regards Ranjit


回答1:


You are casting your NSURLResponse to an NSHTTPURLResponse but this won't automatically expose the actual value you expect in the statusCode property.

Instead, you should check if the error property has been populated and check the code property instead.

if(error)
{
    NSLog(@"error: %@", error.code);

    if(error.code == 401)
    {
        //handle 401 errors
    }
    else if(error.code == 500)
    {
        //handle 500 errors
    }
}
else
{
    //successful request
}


来源:https://stackoverflow.com/questions/28413256/handle-401-status-code-with-sendasynchronousrequestrequest-api-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!