Pregunta

¡Ayuda a hacer una barra de direcciones unificadas en iOS 5 para una aplicación de navegador?Así que aquí está mi barra de direcciones.

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

¿No podría agregar una referencia "otra cosa" para decir si no es una dirección, luego agregue la etiqueta de búsqueda de Google?¿Si es así, cómo?¿Y sabrías cómo usar Bing en lugar 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];
}

¿Fue útil?

Solución

Aquí hay algunos consejos para ayudarlo:

  • use stringByAddingPercentEscapesUsingEncoding: en lugar de su reemplazo "+".
  • Debe verificar si http:// no es un prefijo a la cadena de URL antes de agregarla
  • Debe implementar el protocolo de UIWebViewDelegate para identificar cuando se produce un error al cargar una URL no válida
  • Luego, como retroceso, inicia su búsqueda de Google (ahora puede reemplazar "" por "+") ... o Bing, ¡lo que sea y hasta usted!

Su código debe mirar algo de la siguiente manera:

...
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]
    }
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top