我有一些使用Dribbble API返回Shot的代码,但是,如果JSON中的任何数据为空,应用程序崩溃,我试图实现并捕获它,如果它为null继续,但这似乎不起作用。有人可以建议吗?
非常感谢
詹姆斯
self.JSONString = [NSString stringWithFormat:@"http://api.dribbble.com/shots/1970521"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.JSONString]];
__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data != nil) {
json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(@"Async JSON: %@", json);
}
else {
return;
}
}];
答案 0 :(得分:1)
您需要适当地处理连接错误。 尝试这样的事情:
self.JSONString = [NSString stringWithFormat:@"http://api.dribbble.com/shots/1970521"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.JSONString]];
__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (connectionError != nil || data == nil)
{
NSLog(@"Error loading dribble shot: %@",connectionError);
//TODO: Show an alert to the user with UIAlertView?
}
else
{
NSError *jsonParsingError = nil;
json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError];
if (jsonParsingError != nil || json == nil){
NSLog(@"Error parsing JSON: %@",jsonParsingError);
//TODO: User alert?
}
else
{
NSLog(@"Parsed JSON: %@",json);
//Process parsed JSON, update UI, etc.
//Keep in mind updates to the UI should be done in a main-thread call like this:
dispatch_sync(dispatch_get_main_queue(),^{
//Update UI here
});
}
}
}
}];
答案 1 :(得分:0)
您可以使用第三方Dribbble iOS SDK。它包含所有Dribbble API,提供单行api调用方法,还包括OAuth2集成流和数据模型类。查看:https://github.com/agilie/dribbble-ios-sdk