2010年8月30日月曜日

[iPhone] UIWebView의 링크를Safari로 열기

UIWebView의 링크를 Safari로 열기

참고링크:

결론은 UIWebViewDelegate를 이용한다.

Interface Builder에서 UIWebView의 delegate를 설정하고,


다음의 코드를 추가한다.
// 링크를 클릭했을 때, Safari를 열기위한 처리.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSLog(@"URL = %@", [[request URL] absoluteString]);
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}

return YES;
}


테스트시 사용한 전체 코드
WebViewTestAppDelegate.h
//
// WebViewTestAppDelegate.h
// WebViewTest
//
// Created by BABUKUMA on 10/08/30.
// Copyright babukuma.com 2010. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface WebViewTestAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
IBOutlet UIWebView *webView;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end


WebViewTestAppDelegate.m
//
// WebViewTestAppDelegate.m
// WebViewTest
//
// Created by BABUKUMA on 10/08/30.
// Copyright babukuma.com 2010. All rights reserved.
//

#import "WebViewTestAppDelegate.h"

@implementation WebViewTestAppDelegate

@synthesize window;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch.

[window makeKeyAndVisible];

// WebViewの初期表示
NSLog(@"BABUKUMA : WebViewの初期表示");
NSURL *url = [NSURL URLWithString:@"http://babukuma.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest: request];

return YES;
}

// リンクをクリック時、Safariを起動する為の処理
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSLog(@"URL = %@", [[request URL] absoluteString]);
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}

return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
}


- (void)applicationWillTerminate:(UIApplication *)application {
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
}


- (void)dealloc {
[window release];
[super dealloc];
}


@end