2014-06-10 100 views
1

我想請求safari.app中的外部鏈接。不幸的是它不起作用。我嘗試了How can I open an external link in Safari not the app's UIWebView?的所有代碼,但它們在我的代碼中都不起作用。如何從UIWebView中打開safari.app中的外部鏈接?

你有什麼想法嗎?我的錯誤在哪裏?謝謝你的幫助!

這裏是我的代碼:

#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 

回答

7

設置你的WebView的自我委託,不要忘記!

這個工作對我來說:

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

    return YES; 
} 
相關問題