Créer une barre de recherche d'adresse unifiée dans iOS 5 ?
-
12-12-2019 - |
Question
Aide à créer une barre d'adresse unifiée dans iOS 5 pour une application de navigateur ?Voici donc ma barre d'adresse.
-(IBAction)url:(id)sender {
NSString *query = [urlBar.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
[webPage loadRequest:request];
}
Ne pourrais-je pas ajouter une référence « autre » pour dire que s'il ne s'agit pas d'une adresse, ajouter la balise de recherche Google ?Si c'est le cas, comment?Et sauriez-vous comment utiliser Bing au lieu de Google ?
-(IBAction)googleSearch:(id)sender {
NSString *query = [googleSearch.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSURL *urlQuery = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?hl=en&site=&q=%@", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:urlQuery];
[webPage loadRequest:request];
}
La solution
Voici quelques conseils pour vous aider :
- utiliser
stringByAddingPercentEscapesUsingEncoding:
au lieu de votre remplacement "+". - vous devez vérifier si http:// n'est pas un préfixe à la chaîne URL avant de l'ajouter
- vous devriez mettre en œuvre le
UIWebViewDelegate
protocole pour identifier lorsqu'une erreur se produit lors du chargement d'une URL invalide - puis en guise de solution de repli lancez votre recherche Google (vous pouvez désormais remplacer " " par " + ")...ou Bing, peu importe et à vous de décider !
Votre code devrait ressembler à ceci :
...
webView.delegate = self; // Should appear in your code somewhere
...
-(IBAction)performSearch {
if ([searchBar.text hasPrefix:@"http://"]) {
... // Make NSURL from NSString using stringByAddingPercentEscapesUsingEncoding: among other things
[webView loadRequest:...]
} else if ([self isProbablyURL:searchBar.text]) {
... // Make NSURL from NSString appending http:// and using stringByAddingPercentEscapesUsingEncoding: among other things
[webView loadRequest:...]
} else {
[self performGoogleSearchWithText:searchBar.text]
}
}
- (BOOL)isProbablyURL:(NSString *)text {
... // do something smart and return YES or NO
}
- (void)performGoogleSearchWithText:(NSString *)text {
... // Make a google request from text and mark it as not being "fallbackable" on a google search as it is already a Google Search
[webView loadRequest:...]
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
... // Notify user
if (was not already a Google Search) {
[self performGoogleSearchWithText:searchBar.text]
}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow