2012-08-06 128 views
5

我在线上关注Tutorial,我有2种向Google Places API提交查询的方法。我试图得到一个回应不幸的是,它不工作。我在代码中有一些调试号码。但是,这是代码。Google Places API未返回响应

-(void) queryGooglePlaces{ 
    NSString *url = @"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=myKey"; 

    //Formulate the string as a URL object. 
    NSURL *googleRequestURL=[NSURL URLWithString:url]; 
    NSLog(@"1.5"); 
    // Retrieve the results of the URL. 
    dispatch_async(kBgQueue, ^{ 
     NSData* data = [NSData dataWithContentsOfURL: googleRequestURL]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; 
    }); 
    NSLog(@"2"); 
} 

-(void)fetchedData:(NSData *)responseData { 
    //parse out the json data 
    NSError* error; 
    NSDictionary* json = [NSJSONSerialization 
          JSONObjectWithData:responseData 

          options:kNilOptions 
          error:&error]; 

    //The results from Google will be an array obtained from the NSDictionary object with the key "results". 
    NSArray* places = [json objectForKey:@"results"]; 

    //Write out the data to the console. 
    NSLog(@"Google Data: %@", places); 
    NSLog(@"3"); 
} 

在日志输出变为这样:

2012-08-03 16:40:12.411 sCode[25090:1a303] 1.5 
2012-08-03 16:40:12.411 sCode[25090:1a303] 2 
2012-08-03 16:40:12.512 sCode[25090:1a303] 4 
2012-08-03 16:40:12.751 sCode[25090:1a303] Google Data: (
) 
2012-08-03 16:40:12.751 sCode[25090:1a303] 3 
2012-08-03 16:40:13.628 sCode[25090:1a303] 1 
2012-08-03 16:40:14.129 sCode[25090:1a303] 4 

谁能告诉我怎么回事错了,所以我没没有得到回应? 是的,我在ViewDidLoad方法[self queryGooglePlaces];方法 欣赏帮助家伙!对不起,如果我太冗长了......刚开始尝试学习!

回答

2

鉴于提供的代码,我最好的猜测是你需要通过添加百分号转义来编码你的URL字符串。尝试创建url这样的...

NSString *url = @"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=myKey"; 
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

您通常会作出这样的成一行,但已经表明它作为两行清晰。这会将那些=&转换为正确转义的字符以提供有效的URL。

+0

以及我的网址是不同的 然而,这个特殊的网址,我直接从Google Places API网站拉出来,并简单地更换了我的API密钥。 所以你认为问题只在于网址? – 2012-08-06 18:59:37

+0

确切的URL与您的问题无关。我正在专门讲述如何在将URL发送到服务器进行处理之前对其进行编码。 – 2012-08-06 19:19:38

+0

即使当我添加该行代码 我没有得到回应:( – 2012-08-06 19:43:04