11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Swift】 WKWebViewのAppStoreのリンクをストアアプリで開く

Last updated at Posted at 2016-03-04

WKWebViewのAppStoreのリンクをストアアプリで開く

UIWebViewでAppStoreのリンクをタップすると自動でストアアプリで開いてくれましたが
WKWebViewでは自前で実装する必要があるようです。

やることは以下

  1. WkWebViewの画面遷移をフック
  2. 正規表現でURLがストアへのリンクかチェック
  3. AppStoreのリンクなら、ストアアプリで開く

↓ソースです

swift2.0以降
override func viewDidLoad() {
  super.viewDidLoad()
  // WkWebViewをViewに貼り付け
  self.wkWebView = WKWebView()
  self.view = self.wkWebView!
  var url = NSURL(string:"http://www.yahoo.co.jp/")
  var req = NSURLRequest(URL:url)
  self.wkWebView!.loadRequest(req)
  self.wkWebView.navigationDelegate = self
}

// MARK: - WkWebViewの画面遷移をフック
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    let url = navigationAction.request.URL
    let urlString = ((url) != nil) ? url!.absoluteString : ""
    
    if isMatch(urlString,pattern: "\\/\\/itunes\\.apple\\.com\\/") {
        // AppStoreのリンクなら、ストアアプリで開く
        UIApplication.sharedApplication().openURL(url!)
        decisionHandler(WKNavigationActionPolicy.Cancel)
    }
    decisionHandler(WKNavigationActionPolicy.Allow)
}

// MARK: - 正規表現でマッチング
func isMatch(input: String, pattern:String) -> Bool {
    let regex = try! NSRegularExpression( pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
    let matches = regex.matchesInString( input, options: [], range:NSMakeRange(0, input.characters.count) )
    return matches.count > 0
}
11
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?