【发布时间】:2017-09-21 14:01:33
【问题描述】:
说明:在整个应用程序中,我们使用位于 AppDelegate.m 中的 Web 请求方法从服务器获取数据。我在所有这些请求中都使用了一个令牌。有时来自服务器的响应是 json:{error = "token_not_provided"} 或 {error = "token_expired"}。我需要一种方法来测试 json 是否包含这些错误或正确的 json 数据。如果发回的数据是这些错误之一,我们需要返回登录屏幕以在登录时获取新令牌。目前,我无法在请求方法中检测到这些错误,因此如果它们发生,应用程序将永远崩溃,因为无法让您重新登录。下面是 App Delegate 中的请求方法:
-(void)makeRequest:(NSString*)urlString method:(NSString*)method params:(NSMutableDictionary*)params onComplete:(RequestBlock)callback {
// create the url
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", BASE_URL, urlString]];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
NSString *token = [keychainItem objectForKey:(__bridge id)(kSecAttrAccount)];
if(!token){
token = @"NO_TOKEN";
}
// set the method (GET/POST/PUT/UPDATE/DELETE)
[request setHTTPMethod:method];
[request addValue:[@"Bearer " stringByAppendingString:token] forHTTPHeaderField:@"Authorization"];
// if we have params pull out the key/value and add to header
if(params != nil) {
NSMutableString * body = [[NSMutableString alloc] init];
for (NSString * key in params.allKeys) {
NSString * value = [params objectForKey:key];
[body appendFormat:@"%@=%@&", key, value];
}
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
}
// submit the request
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
// do we have data?
if(data && data.length > 0) {
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
// if we have a block lets pass it
if(callback) {
callback(json);
}
HERE IS WHERE I WANT TO TEST IF WE HAVE ERROR JSON or PROPER JSON
}
}];
}
【问题讨论】:
-
if([[data valueForKey:@"error"] isEqualToString:@"token_not_provided"] || [[data valueForKey:@"error"] isEqualToString:@"token_expired"]) { 我可以'不要使用它来测试,因为如果它包含正确的 json 会崩溃 }
-
不要在评论中添加额外信息。 Edit您的问题以及所有相关详细信息。
-
您可以将
NSURLResponse转换为NSHTTPURLResponse并检查http 状态码。令牌错误大多是401
标签: ios objective-c json