簡體   English   中英

從UIWebView在Safari中打開特定鏈接

[英]Open specific link in Safari from UIWebView

我有一個UIWebView ,它加載本地index.html文件。

但是,我要在Safari中打開此html文件中的外部鏈接,而不是在UIWebView中內部打開。

通過說一個UIButton在野生動物園中打開鏈接非常簡單:

UIApplication.sharedApplication().openURL(NSURL(string: "http://www.stackoverflow.com"))

從外部鏈接打開Instagram應用程序也像超級按鈕一樣工作。

<a href="instagram://media?id=434784289393782000_15903882">instagram://media?id=434784289393782000_15903882</a>

所以我的第一步雖然是做這樣的事情:

<a href="safari://stackoverflow.com">Open in Safari</a>

但是,這似乎不起作用,然后我閱讀了有關使用webView:shouldStartLoadWithRequest:navigationType:

但是,每個設法在Safari中打開外部鏈接的人都在用Obj-C編寫程序,而我在用Swift編寫程序時並不太熟悉。

使用Swift代碼更新:

import UIKit

class AccessoriesViewController: UIViewController, UIWebViewDelegate {


    @IBOutlet weak var webView:UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()


        if let url = NSBundle.mainBundle().URLForResource("accessories", withExtension: "html") {
            webView.loadRequest(NSURLRequest(URL: url))
        }



    }
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return UIStatusBarStyle.LightContent;
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let url = request.URL where navigationType == UIWebViewNavigationType.LinkClicked {
            UIApplication.sharedApplication().openURL(url)
            return false
        }
        return true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

這是您可以做到的!

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let url = request.URL where navigationType == UIWebViewNavigationType.LinkClicked {
            UIApplication.sharedApplication().openURL(url)
            return false
        }
        return true
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM