2012-12-22 43 views
-1

我是新iOS iOS 我想調用谷歌API指示服務,並解析它,我知道如何通過使用post方法調用Web服務,但我不知道如何整合參數轉換爲url,並從中獲取json響應。 請幫助我。如何調用谷歌API服務使用

+0

你在尋找'[NSString stringWithFormat:]'? – 2012-12-22 12:30:02

+0

檢查此鏈接http://www.edumobile.org/iphone/iphone-programming-how-to-implement-core-location-and-the-google-xml-weather-api-on-the-iphone/我可以幫你。 – jamil

回答

1

請參閱下面的代碼,你會得到一些想法。

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
dispatch_async(queue, ^{ 
    NSString *stringOrigin = @"Surandai"; 
    NSString *stringDestination = @"Coimbatore"; 
    NSData *dataDirection = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", stringOrigin, stringDestination]]]; 
    NSDictionary *dictionaryDirection = [NSJSONSerialization JSONObjectWithData:dataDirection options:NSJSONReadingAllowFragments error:nil]; 
    dispatch_sync(dispatch_get_main_queue(), ^{ 
     NSLog(@"dictionaryDirection - %@", dictionaryDirection); 
     //Do UI update here 
    }); 
}); 
+0

感謝Paramasivan Samuttiram,但是有問題,我的出發地和目的地是多個單詞,即他們之間有空間(例如34 st penn station),這是什麼解決方案? – prabhu

+0

使用stringByAddingPercentageEscapesUsingEncoding方法。 –

+0

非常感謝你.. – prabhu

1

用於傳遞數據使用NSURLConnection發佈後,您可以使用setHTTPBody方法。

您可以使用下面的代碼:

NSURL *aUrl = [NSURL URLWithString:@"yourURL"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl 
             cachePolicy:NSURLRequestUseProtocolCachePolicy 
            timeoutInterval:60.0]; 

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                  delegate:self]; 

[request setHTTPMethod:@"POST"]; 
NSString *postString = @"username=Midhun&password=Midhun"; 
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

而且響應數據可以通過didReceiveData委託方法得到。您需要將接收到的數據附加到NSMutableData對象以供進一步使用。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [receivedData appendData:data]; 
}