如何在UitextView中集成google place finder?

时间:2015-10-17 08:33:35

标签: ios objective-c iphone

我在IOS中构建一个应用程序,它有一个UITextView用户输入类似他的地址,但没有整个,谷歌应该预测并完成地址,我已经有一个来自谷歌的密钥,请帮忙我执行这个,我不明白如何

2 个答案:

答案 0 :(得分:0)

您必须实施UITextFieldDelegate, 在textField:shouldChangeCharactersInRange:replacementString方法中,你应该有类似的东西:

   -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *substring = [NSString stringWithString:textField.text];
    substring = [substring stringByReplacingCharactersInRange:range withString:string];
    substring = [substring stringByReplacingOccurrencesOfString:@" " withString:@""];

    // your code to send the search string to google place API  
    return YES;
}

当您对google places API的搜索请求完成后,请不要忘记使用以下代码重新加载UITableView的数据:[yourTable reloadData]

希望这有帮助。

干杯。

答案 1 :(得分:0)

首先,您必须从- (void)textViewDidChange:(UITextView *)textView委托方法获取更新文本。然后使用谷歌地图SDK搜索最匹配的位置。

- (void)textViewDidChange:(UITextView *)textView {
     [self searchLocationWithText:textView.text];
}

- (void)searchLocationWithText:(NSString *)searchText
{
     NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/textsearch/json?query=%@&key=%@", searchText, kGoogleSDKBrowserKey];
     NSURL *googleRequestURL = [NSURL URLWithString:url];
     // Retrieve the results of the URL.
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          NSData *data = [NSData dataWithContentsOfURL:googleRequestURL];
          NSError *error = nil;
          NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

          if ([[json objectForKey:@"status"] isEqualToString:@"OK"])  {
              NSArray *locations = [json objectForKey:@"results"];
              NSDictionary *place = [locations firstObject];
              NSString *locationName = [place objectForKey:@"name"];
              // Set location name to your textView
              textView.text = locationName;
          }
     });
}

此处,kGoogleSDKBrowserKey是您注册的API密钥。另请参阅how to register for Google Places