检查NSURLSessionDataTask的响应值

时间:2014-06-16 03:43:07

标签: ios objective-c nsurlsessionconfiguration

我是iOS开发的完全新手,正在开发我的第一个应用程序。我正在与需要用户使用其用户名和密码登录的Web服务连接。我想检查并确保他们输入正确的用户名和密码,然后将其保存在钥匙串中,这样我就可以使用凭据进行简单的获取请求。我想查看我得到的响应,看看是否收到错误消息。这是我编写的代码,它对Web服务执行GET请求。

-(BOOL)checkCredentials:(NSString *)username withPassword:(NSString *)password{

    NSString *requestString = @"some_web_service_url";
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    NSData *userPasswordData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
    NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential];

    NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.HTTPAdditionalHeaders=@{@"Authorization":authString};

    self.session=[NSURLSession sessionWithConfiguration:sessionConfig];

    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        NSLog(@"%@", jsonObject);

    }];

    [dataTask resume];
    //I think error checking logic should go here.
}

我想查看我的jsonObject是否有错误代码,但是我可以在[dataTask resume]之后执行此操作吗?有没有更好的方法来检查返回代码?我相信jsonObject将返回json所以我想我想检查标题的返回值,但我不完全确定。对不起,如果这是一个简单的问题,但我是新的,有点困惑。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以通过将NSURLResponse强制转换为会话数据任务完成块中的NSHTTPURLResponse来检索HTTP返回码,并检查statusCode属性。

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *user;         // Update to your user name
    NSString *password;     // Update to your use name password

    [self checkCredentials:user withPassword:password completion:^(BOOL authorized) {
        if (authorized) {
            // Save the credentials

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update your UI if needed.
            });
        } else {
            // Unauthorized
            //
            // Inform the user if needed.
        }
    }];
}

- (void)checkCredentials:(NSString *)username
            withPassword:(NSString *)password
              completion:(void (^)(BOOL))authorized
{
    NSString *requestString;    // Update to your Web Service URL
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    NSData *userPasswordData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
    NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential];

    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.HTTPAdditionalHeaders = @{ @"Authorization" : authString };
    self.session = [NSURLSession sessionWithConfiguration:sessionConfig];

    NSURLSessionDataTask *dataTask =
    [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSHTTPURLResponse *httpURLResponse = (NSHTTPURLResponse *)response;
        NSUInteger statusCode = httpURLResponse.statusCode;

        switch (statusCode) {
            case 200:                   // Authorized
                authorized(YES);
                break;
            case 401:                   // Unauthorized
                authorized(NO);
                break;
            default:
                // Unauthorized
                //
                // For a copmlete list of HTTP response status codes see http://www.ietf.org/rfc/rfc2616.txt
                // also be aware that not all Web Services return the same status codes.
                authorized(NO);
                break;
        }
    }];

    [dataTask resume];
}