1

I want to request external links in safari.app. Unfortunately it doesn't work. I have tried all codes from How can I open an external link in Safari not the app's UIWebView? but they all doesn't work in my code.

Have you any ideas? Where is my mistake? Thank you for help!

Here's my Code:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


- (void)viewDidLoad
{
    [self.iPhoneWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com"]]];
    [self.iPadWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com"]]];

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    //  open External Links (not beginning with http://www.example.com in Safari.app
    if (
        (navigationType == UIWebViewNavigationTypeLinkClicked) &&
        ( ![[[request URL] absoluteString] hasPrefix:@"http://www.example.com"])
        ) {

        [[UIApplication sharedApplication] openURL:request.URL];
        return NO;
    }

    //open Internal links in uiwebview
    return YES;
}


- (void)displayActivityControllerWithDataObject:(id)obj {
    UIActivityViewController* vc = [[UIActivityViewController alloc]
                                    initWithActivityItems:@[obj] applicationActivities:nil];
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    // starting the load, show the activity indicator in the status bar
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // finished loading, hide the activity indicator in the status bar
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    // load error, hide the activity indicator in the status bar
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    // report the error inside the webview
    NSString* errorString = [NSString stringWithFormat:
                             @"<html><center><font size=+5 color='red'>Ein Fehler ist aufgetreten<br>%@</font></center></html>",
                             error.localizedDescription];
    [self.iPhoneWebView loadHTMLString:errorString baseURL:nil];
}



@end
Community
  • 1
  • 1
user3725634
  • 11
  • 1
  • 2

1 Answers1

7

Set the delegate of your webview to self, dont forget !

This works for me :

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

    return YES;
}
Neva
  • 1,330
  • 9
  • 11