Я довольно новичок в iOS. Я пытаюсь использовать автозаполнение google и работать с ней ... в основном. :)(iOS) Как добавить место на автозаполнение google для строки поиска
У меня есть UISearchBar, и когда пользователь вводит строку в строке поиска, она автозаполняется с предсказанными местами (предприятиями). Однако, когда я нажимаю на пробел, код внезапно переходит к следующему методу: - (void) connection: (NSURLConnection *) connection didFailWithError: (NSError *) error
Мне нужен способ поиска строки с пробелами. Например, пользователь вводит «Лондон», это нормально. Как только «лондонская англия» пойдет в метод ошибок и сработает. Также вы технически не сможете писать «англия», ошибка происходит, как только пространство после Лондона.
Это страница, которая предоставляет информацию, но я не могу видеть, что я после: https://developers.google.com/places/documentation/autocomplete#location_biasing
Ниже приведены методы, которые я считаю наиболее актуальной.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.autoCompleteResults = [NSJSONSerialization JSONObjectWithData:self.autoCompleteNSData options:nil error:nil];
//test logging
NSLog(@"Connection did finish loading");
NSLog(@"Auto Complete Results - Dictionary: %@ ", self.autoCompleteResults);
//parse the auto complete results
self.filteredStrings = [self.autoCompleteResults objectForKey:@"predictions" ];
NSLog(@"Auto Complete Results - Array: %@", self.filteredStrings);
int i = [self.filteredStrings count];
NSLog(@"Count of array: %i", i);
int n = 0;
for (n = 0; n < i;n= n+1) {
NSString *tempDescription = [[self.filteredStrings objectAtIndex:n]objectForKey:@"description"];
NSLog(@"tempDescription: %@", tempDescription);
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection didfail with error");
UIAlertView *connectionErrorView = [[UIAlertView alloc]initWithTitle:@"Connection error" message:@"There is a problem with the connection. Please ensure that you are connected to 3G or Wi-Fi" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[connectionErrorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
//self.filteredStrings is a NSMutableArray (not dictionary)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (self.filteredStrings) {
cell.textLabel.text = [[self.filteredStrings objectAtIndex:indexPath.row]objectForKey:@"description"];
}else{
cell.textLabel.text = @"Currently no results";
}
return cell;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//To check if alphanumerical characters have been entered
NSString *alphaStr = @"aA09";
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
BOOL valid = [[alphaStr stringByTrimmingCharactersInSet:alphaSet] isEqualToString:searchText];
NSLog(@"SearchText String: %@", searchText);
//The if is needed because without it the program crashes when you clear the field via the 'X' button in search bar
if (valid) {
NSLog(@"SearchText passed !SearchText: %@", searchText);
}else{
NSLog(@"SearchText should be full: %@", searchText);
NSString *autoCompleteUrl = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&types=establishment&location=37.76999,-122.44696&radius=500&sensor=true&key=Mykey", searchText];
NSURL *url = [NSURL URLWithString:autoCompleteUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
[self.autoCompleteTableView reloadData];
}
}
Я не могу использовать метод UrlEncode на SearchText ...: - S – Anthony
К сожалению, попробуйте следующее: [SearchText stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding] – rjowens
Великий работал лакомство. Благодаря! – Anthony