我在我的应用中实现了Web服务。我的方式很典型。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Web Service xxx,yyy are not true data
NSString *urlString = @"http://xxx.byethost17.com/yyy";
NSURL *url = [NSURL URLWithString:urlString];
dispatch_async(kBackGroudQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: url];
[self performSelectorOnMainThread:@selector(receiveLatest:) withObject:data waitUntilDone:YES];
});
return YES;
}
- (void)receiveLatest:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSString *Draw_539 = [json objectForKey:@"Draw_539"];
....
控制台错误消息:
*由于未捕获的异常而终止应用程序'NSInvalidArgumentException',原因:'数据参数为nil'
当我的iPhone连接到Internet时,该应用程序将成功运行。但是,如果断开与Internet的连接,则应用程序将在NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
上崩溃您能告诉我如何处理此错误吗? NSError
有帮助吗?
错误告诉您“ responseData”为零。避免异常的方法是测试“ responseData”,并且如果它为nil,则不调用JSONObjectWithData。而是做出反应,但是您认为应该针对此错误情况。
在将其传递给responseData
方法之前,您没有检查JSONObjectWithData:options:error:
是否为零。
可能您应该尝试以下方法:
- (void)receiveLatest:(NSData *)responseData {
//parse out the json data
NSError* error;
if(responseData != nil)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSString *Draw_539 = [json objectForKey:@"Draw_539"];
}
else
{
//Handle error or alert user here
}
....
}
EDIT-1:为了好的做法,应该在error
方法之后检查此JSONObjectWithData:options:error:
对象,以检查是否将JSON数据成功转换为NSDictionary。
- (void)receiveLatest:(NSData *)responseData {
//parse out the json data
NSError* error;
if(responseData != nil)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if(!error)
{
NSString *Draw_539 = [json objectForKey:@"Draw_539"];
}
else
{
NSLog(@"Error: %@", [error localizedDescription]);
//Do additional data manipulation or handling work here.
}
}
else
{
//Handle error or alert user here
}
....
}