0

我是 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,所以我想我想检查标题中的返回值,但我不完全确定。对不起,如果这是一个简单的问题,但我是新手,有点困惑。任何帮助将不胜感激!

4

1 回答 1

0

NSURLResponse您可以通过在会话数据任务完成块中强制转换来检索 HTTP 返回代码NSHTTPURLResponse并检查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];
}
于 2014-10-16T16:59:59.077 回答