google autocompelte custom using textfield in ios



我想在ios中使用textfield将Google自动完成与自定义UI一起使用。我已经尝试了许多第三方,并且所有人都在使用谷歌网络API,谷歌网络API有一些限制,但我想使用iOS移动API,因为它是免费的。所以请帮忙。

  _resultsViewController = [[GMSAutocompleteResultsViewController alloc] init];
  _resultsViewController.delegate = self;
  _searchController = [[UISearchController alloc]
                           initWithSearchResultsController:_resultsViewController];
  _searchController.searchResultsUpdater = _resultsViewController;

所以我想知道我们如何在iOS中使用TextField创建Google Autocompelte自定义。

杂注标记:GooglePlace API

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self queryGooglePlaces:newString];
   return true;
}

杂注标记:自动完成查询

-(void) queryGooglePlaces: (NSString *) searchStr{
searchStr = [searchStr stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?key=%@&input=%@",kGOOGLE_API_KEY,searchStr];

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

杂注标记:获取数据

- (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:@"predictions"];
//Write out the data to the console.
NSLog(@"Google Data: %@", places);
[searchResultPlaces removeAllObjects];
for (int i =0; i < places.count ; i++) {
    [searchResultPlaces addObject:[[places valueForKey:@"description"] objectAtIndex:i]];//searchResultPlaces is nsmutable array to store result data
}
NSLog(@"%@",searchResultPlaces);
if (searchResultPlaces.count > 1) {
    _GoogleAddressView.hidden = NO;
//_GoogleAddressView is the view in which table is located. you can use it as per your design.
    _addressTable.hidden = NO;

}else{
    _GoogleAddressView.hidden = YES;
//_GoogleAddressView is the view in which table is located. you can use it as per your design.
    _addressTable.hidden = YES;
}
[_addressTable reloadData];
// address tbl
}

相关内容

  • 没有找到相关文章

最新更新