ios 8上不支持的URL

时间:2015-03-06 09:40:27

标签: ios8 nsurl nsurlrequest

我尝试使用以下代码从Google地方获取json:

NSString *query = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%i&types=%@&sensor=true&key=%@", center.latitude, center.longitude, rad, types, kGOOGLE_API_KEY];
NSLog(@"%@",query);
NSURL *googleRequestURL=[NSURL URLWithString:query];
[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:googleRequestURL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        NSLog(@"Error fetching data: %@",[error description]);
    } else {
        //To-do
    }
}];

生成的网址为:https://maps.googleapis.com/maps/api/place/search/json?location=37.337566,-122.041202&radius=1000&types=accounting|bowling_alley|doctor&sensor=true&key=MY_KEY

(由于某些原因,我的密钥被忽略了)

从笔记本电脑的浏览器中可以正常工作,但返回错误:

Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x7fe47bc138f0 {NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7fe47be9dbe0 "unsupported URL"}

我尝试使用http而不是https(在浏览器中它返回一个带有一些错误消息的json,但仍然返回一些内容)但没有成功。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

这就是我解决问题的方法。祝好运!

NSString *google = @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=500&types=%@&key=%@";  
NSString *link = [NSString stringWithFormat:google, coordinate.latitude, coordinate.longitude, types, GOOGLE_KEY];
NSURL *url = [NSURL URLWithString:[link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];  
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];