2010-12-15 23 views
27

Tengo una aplicación con UIWebView dentro de UIViewController. Me carga HTML desde un servicio web como una cadena como esta:¿Abrir enlaces en Safari en lugar de UIWebVIew?

self.webView loadHTMLString:_string baseURL:nil 

¿Es posible que los enlaces HTML en esta cadena para abrir en el navegador y no en el UIWebView en mi aplicación? ¿Cómo puedo hacer esto?

He intentado esto en el UIViewController que "hosts" del UIWebView:

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { 
    if (navigationType == UIWebViewNavigationTypeLinkClicked) { 
    [[UIApplication sharedApplication] openURL:[request URL]]; 
    return NO; 
    } 
    return YES; 
} 

No parece estar funcionando ....

¿Alguna idea?

+0

El código que has enviado debería funcionar, asumiendo que [request URL] es un tipo de URL que puede manejar Safari (o alguna otra aplicación en el dispositivo iOS). ¿Puedes publicar un ejemplo de una de las URL que tocaría un usuario? – Greg

Respuesta

22

¿Ha establecido el delegado de la UIWebView a su UIViewController? No hay nada obviamente mal con su código, por lo que puedo ver, por lo que es probable que sea algo así.

+0

sí, lo hice. pero lo agregué de la siguiente manera: no estoy seguro si es incorrecto o correcto, pero ut parece estar funcionando: webView.delegate = self; ¿está mal agregar esto? – treasure

+1

Agregar '' a la definición de clase solo significa que implementa el protocolo. No significa que sea el delegado, solo que puede ser. Necesitas el 'webView.delegate = self' (o puedes hacerlo en Interface Builder). –

+0

@Yar La respuesta ya dice eso. El comentario aclara la diferencia entre el protocolo 'UIWebViewDelegate' y la propiedad' delegate'. –

-3

Sí, en su etiqueta hipervínculo añadir

target="blank" 

Y un signo de interrogación va a estar bien, gracias

+4

El ajuste 'target =" blank "' or 'target =" _ blank "' parece no tener ningún efecto. En iOS 4.3, los enlaces aún se abren dentro de UIWebView. – Palimondo

21

Añadir esto en clase ..

@interface yourViewController : UIViewController 
<UIWebViewDelegate> 

Añadir esta perspectiva se carga

- (void)viewDidLoad 
{ 
    [description loadHTMLString:string baseURL:nil]; 
     description.delegate = self; 
} 

Añadir esto en su archivo .m

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType { 
    if (inType == UIWebViewNavigationTypeLinkClicked) { 
     [[UIApplication sharedApplication] openURL:[inRequest URL]]; 
     return NO; 
    } 

    return YES; 
} 

Nota:

UIWebView *description; 
@synthesize description; 

¡Entonces funcionará perfectamente de la manera que usted se merece .. !! :)

+0

Asegúrese de escribir en mayúscula la V en webView como: - (BOOL) webView: (UIWebView *) inWeb shouldStartLoadWithRequest: (NSURLRequest *) inRequest navigationType: (UIWebViewNavigationType) en Tipo – dinjas

+0

Estoy usando UIWebView para mostrar citas de la web con un enlace en el final de cada cita a la fuente. Esto funcionó para mí para abrir enlaces en Safari en lugar de en UIWebView. – JScarry

1

Establecer la delegado del UIWebView a su UIViewController después de que el uso de este método UIWebView y compruebe el estado, por ejemplo ahora en vista web URL actual es google.com, si supongamos que usted ha hecho clic en el gmail url contiene la cadena con gmail. Use el siguiente método para abrir un navegador Safari y cargar automáticamente esa url.

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType { 
    if (inType == UIWebViewNavigationTypeLinkClicked) { 
     NSURL *url = [inRequest URL]; 
     if ([[url absoluteString] rangeOfString:@"gmail"].location == NSNotFound) { 
      [[UIApplication sharedApplication] openURL:[inRequest URL]]; 
      return NO; 
     } 
    } 
    return YES; 
} 
0

Si ya ha configurado correctamente el UIWebViewDelegate, simplemente haciendo

self.webView loadHTMLString:_string baseURL:nil 
self.webView.delegate = self; 

debería funcionar

0

añadir esta línea ( self.webview.delegate = sí; )

Para Ejemplo en viewController.m

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; 
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil]; 
[self.webview loadHTMLString:htmlString baseURL:nil]; 
self.webview.delegate = self; 
0

Apple presentó un Controlador de Safari View en iOS 9. Safari View Controller ofrece todas las funciones que el usuario espera de Safari en su aplicación sin tener que abandonarla.

En primer lugar tenemos que importar Safari Servicios

#import <SafariServices/SafariServices.h> 

Para C Objetivo: -

NSString *yourUrl = @"http://yourURL"; 
SFSafariViewController *svc= [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString: yourUrl]]; 
[self presentViewController:svc animated:YES completion:nil]; 

para SWIFT: -

let svc = SFSafariViewController(URL: NSURL(string: self.urlString)!) 
self.presentViewController(svc, animated: true, completion: nil) 
Cuestiones relacionadas