检查 NSURLSessionDataTask 的响应值
Posted
技术标签:
【中文标题】检查 NSURLSessionDataTask 的响应值【英文标题】:Check response value of NSURLSessionDataTask 【发布时间】:2014-06-16 03:43:07 【问题描述】:我是 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】:您可以通过在会话数据任务完成块中将NSURLResponse
强制转换为NSHTTPURLResponse
并检查statusCode
属性来检索HTTP 返回代码。
- (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];
【讨论】:
以上是关于检查 NSURLSessionDataTask 的响应值的主要内容,如果未能解决你的问题,请参考以下文章
NSURLSessionDataTask 内存警告应用程序崩溃
appdelegate 中的 NSURLSessionDataTask
使用 NSURLSessionDataTask 显示文件下载进度