2012-08-06 100 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