UIWebView内に表示されたリンクをクリックした場合に、UIWebView内で表示する代わりに、Safariを起動して表示する方法を紹介します。
ソースコード例
Empty ApplicationにUIWebViewを設置し、その中に外部リンク(Yahoo.co.jpへのリンク)を表示する例。httpから始まるリンクは、UIView内で表示するのではなく、Safariを起動して表示する。webView.delegate = selfの部分で警告が表示されるので、インターフェースにUIWebViewDelegateを追加しておく。
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 460)];
[webView loadHTMLString:@"<a href='http://www.yahoo.co.jp'>Yahoo</a>" baseURL:nil];
webView.delegate = self;
[self.window addSubview:webView];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked
|| navigationType == UIWebViewNavigationTypeOther)
{
NSString* scheme = [[request URL] scheme];
if([scheme compare:@"http"] == NSOrderedSame) {
[[UIApplication sharedApplication] openURL: [request URL]];
return NO;
}
}
return YES;
}
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 460)];
[webView loadHTMLString:@"<a href='http://www.yahoo.co.jp'>Yahoo</a>" baseURL:nil];
webView.delegate = self;
[self.window addSubview:webView];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked
|| navigationType == UIWebViewNavigationTypeOther)
{
NSString* scheme = [[request URL] scheme];
if([scheme compare:@"http"] == NSOrderedSame) {
[[UIApplication sharedApplication] openURL: [request URL]];
return NO;
}
}
return YES;
}