1

按照本教程:http ://www.raywenderlich.com/5492/working-with-json-in-ios-5 ,我制作了这样的简单应用程序:

#define kLatestKivaLoansURL [NSURL URLWithString: @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"] 

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL];
        NSError* error;
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data 
                                                             options:kNilOptions
                                                               error:&error];
        NSArray* latestLoans = [json objectForKey:@"loans"];
        NSLog(@"Error: %@",error);
        NSLog(@"loans: %@",latestLoans); 

        dispatch_async(dispatch_get_main_queue(), ^(){
            self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
            self.window.rootViewController = self.viewController;
            [self.window makeKeyAndVisible];
        });

    });

    return YES;
}

@end

当网络不正常或 JSON 链接错误时,我得到相同的中断:“ *由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'数据参数为零”

如何捕捉这个错误?我只想显示一条警报消息,而不是中断。

解析 JSON 数据时有多少种错误?

4

1 回答 1

5

您应该检查NSData* data它是否为零?如果它为零,那么你不应该运行代码行

NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data 
                                                             options:kNilOptions
                                                               error:&error];

当您尝试将nil数据转换为Dictionary.

您还可以通过在代码中实现可达性类来检查网络可用性。一个示例应用程序演示了如何使用 SystemConfiguration 框架来监控 iPhone 或 iPod touch 的网络状态

http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

于 2013-01-29T04:03:26.213 回答