我使用以下代码获取特定地址的地理编码响应
NSString *address = @"Doha,Qatar";
NSLog(@"address : %@",address);
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat: @"http://www.maps.google.com/maps/api/geocode/json?address=%@&sensor=false", esc_addr];
NSURL *url=[NSURL URLWithString:req];
NSLog(@"url : %@",url);
NSData *data=[NSData dataWithContentsOfURL:url];
NSLog(@"data : %@",data);
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:&error];
NSLog(@"The JSON Object: %@ Or Error is: %@", response, error);
但是响应始终为空。
回应,
2014-11-27 16:35:48.961 MyProj[15279:254055] address : Doha,Qatar
2014-11-27 16:35:48.961 MyProj[15279:254055] url : http://www.maps.google.com/maps/api/geocode/json?address=Doha,Qatar&sensor=false
2014-11-27 16:35:49.005 MyProj[15279:254055] data : (null)
2014-11-27 16:35:49.008 MyProj[15279:254055] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
但是当我在眉毛中打开URL时,它会将输出显示为
{
"results" : [
{
"address_components" : [
{
"long_name" : "Doha",
"short_name" : "Doha",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Doha",
"short_name" : "Doha",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Qatar",
"short_name" : "QA",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Doha, Qatar",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 25.4125783,
"lng" : 51.6281212
},
"southwest" : {
"lat" : 25.1954283,
"lng" : 51.4307964
}
},
"location" : {
"lat" : 25.286667,
"lng" : 51.533333
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 25.4125783,
"lng" : 51.6281212
},
"southwest" : {
"lat" : 25.1954283,
"lng" : 51.4307964
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
空响应的原因是什么,
感谢您的任何建议。
答案 0 :(得分:0)
我测试了你的代码,它运行正常。
数据参数不为null。它包含json的信息。
所以,也许你必须检查这些
答案 1 :(得分:0)
感谢所有建议。 dataWithContentsOfURL:
有时不适合我。
所以我使用了NSURLConnection。现在它运作良好。
以下是我所做的更改。
NSString *address = @"Doha,Qatar";
NSLog(@"address : %@",address);
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat: @"http://www.maps.google.com/maps/api/geocode/json?address=%@&sensor=false", esc_addr];
NSURL *url=[NSURL URLWithString:req];
NSData *theData = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
NSDictionary *googleResponse = [NSJSONSerialization JSONObjectWithData:theData
options:0
error:nil];