Ryusuke Fuda's Tech Blog

Softweare Enginier about Web, iOS, Android.

iOS webviewで特定URLのみブラウザ起動

■ webview内で特定URLのみsafari起動させる
GooglePlayへのリンクだけsafari起動させる

■下準備として.hファイルにwebviewをdelegateさせる

@interface FirstViewController : UIViewController<UIWebViewDelegate>

■ .m ファイル

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    _topWebView.delegate = self;

    //webview起動
    NSURL *reqUrlRaw = [NSURL URLWithString:@"http://google.com"];
    NSURLRequest *reqUrl = [NSURLRequest requestWithURL: reqUrlRaw];
    [self.topWebView loadRequest:reqUrl];
    
    
}

//webview内でユーザーがタッチしたりイベントがあると自動で呼ばれる関数
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
        NSString *checkURL = [request.URL absoluteString];
        //チェックするURL
        NSRange linkMatch  = [checkURL  rangeOfString:@"://play.google.com"]; 
        
        if (linkMatch.location != NSNotFound) {
            [[UIApplication sharedApplication] openURL:request.URL];
            return NO;
        }
    
    return YES;
}

参考)
http://pplace.jp/2013/02/1332/