说明:在整个应用程序中,我们使用位于 AppDelegate.m 中的 Web 请求方法从服务器获取数据。我在所有这些请求中都使用了 token 。有时服务器的响应是 json:{error = "token_not_provided"} 或 {error = "token_expired"}。我需要一种方法来测试 json 是否包含这些错误或正确的 json 数据。如果发回的数据是这些错误中的任何一个,我们需要返回登录屏幕以在登录时获取新的 token 。现在,我无法在请求方法中检测到这些错误,所以如果它们发生,应用程序将永远崩溃,因为没有办法让您返回登录。下面是 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
}
}];
最佳答案
如果您可以修改服务器上的接口(interface),您可以发送一个 bool 值来确定请求是否成功。诸如“成功”之类的东西 = 1 或 0。
检查错误消息是危险的,如果消息发生变化,您的应用程序将崩溃。如果你想这样做,你需要检查键“error”是否存在,然后检查它包含什么。
// Check if key is available.
if ([json.keys containsObject:@"error"]) {
if ([json[@"error"] isEqualToString:@"token_not_privided"] || [json[@"error"] isEqualToString:@"token_expired"]) {
// Token is invalid
} else {
// Something different went wrong.
}
}
// Nothing is wrong, lets inform the caller.
else {
if (callback) {
callback(json);
}
}
您应该检查 json 而不是数据。
关于ios - 如何测试 Json 响应是否包含错误或正确的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346020/