这是我的问题。如果我的应用程序无法加载远程JSON文件,如何显示错误?我在电脑上关闭了wifi,然后在模拟器中运行了应用程序。它NSLog记录连接时应显示的消息。我怎样才能解决这个问题?感谢。
这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *jsonStr = @"http://xxx.com/server.php?json=1";
NSURL *jsonURL = [NSURL URLWithString:jsonStr];
// NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
// NSError *jsonError = nil;
NSURLRequest *jsonLoaded = [NSURLRequest requestWithURL:jsonURL];
if(!jsonLoaded) {
UIAlertView *alertView = [[UIAlertView alloc] init];
alertView.title = @"Error!";
alertView.message = @"A server with the specified hostname could not be found.\n\nPlease check your internet connection.";
[alertView addButtonWithTitle:@"Ok"];
[alertView show];
[alertView release];
NSLog(@"No connection, JSON not loaded...");
}
else {
NSLog(@"JSON loaded and ready to process...");
}
}
答案 0 :(得分:1)
您的代码只是创建请求。它实际上并不获取数据。您需要使用NSURLConnection
来获取数据。
有多种方法可以获取数据。此示例适用于iOS 5.0或更高版本:
NSOperationQueue *q = [[[NSOperationQueue alloc] init] autorelease];
NSURLRequest *jsonRequest = [NSURLRequest requestWithURL:jsonURL];
[NSURLConnection sendAsynchronousRequest:jsonRequest
queue:q
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// data was received
if (data)
{
NSLog(@"JSON loaded and ready to process...");
// ... process the data
}
// No data received
else
{
NSLog(@"No connection, JSON not loaded...");
// ... display your alert view
}
}];
答案 1 :(得分:0)
你还没有真正要求任何东西。阅读here了解如何发出请求。
基本上,您要做的是实现NSURLConnectionDelegate协议并覆盖connection:didFailWithError:
函数来侦听失败事件。