我想在safari.app中请求外部链接。不幸的是它不起作用。我已经尝试了How can I open an external link in Safari not the app's UIWebView?中的所有代码,但它们都不适用于我的代码。
你有什么想法吗?我的错误在哪里?谢谢你的帮助!
这是我的代码:
#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
答案 0 :(得分:7)
将webview的代表设置为self,别忘了!
这对我有用:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}