使用ios

时间:2017-06-19 05:24:32

标签: ios xcode google-places-api

我想在ios中使用自定义ui使用文本字段来使用谷歌自动完成功能。 我已经尝试了很多第三方,所有使用谷歌网络API和谷歌网络API有一些限制,但我想使用ios移动api,因为它是免费的。所以请帮忙。

  _resultsViewController = [[GMSAutocompleteResultsViewController alloc] init];
  _resultsViewController.delegate = self;

  _searchController = [[UISearchController alloc]
                           initWithSearchResultsController:_resultsViewController];
  _searchController.searchResultsUpdater = _resultsViewController;

所以我想知道如何使用ios中的textfield创建google autocompelte自定义。

1 个答案:

答案 0 :(得分:0)

pragma mark: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;
}

pragma mark:autoCompletequery

-(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];
});
}

pragma mark:获取数据

- (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

}