【问题标题】:Open specific link in Safari from UIWebView从 UIWebView 在 Safari 中打开特定链接
【发布时间】:2016-04-16 22:26:03
【问题描述】:

我有一个UIWebView,它加载了一个本地 index.html 文件。

但是我在这个 html 文件中有一个外部链接,我想在 Safari 中打开,而不是在 UIWebView 内部打开。

UIButton 说在 Safari 中打开一个链接很简单:

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.
    }


}

【问题讨论】:

    标签: html ios swift safari uiwebview


    【解决方案1】:

    你可以这样做!

    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
        }
    

    【讨论】:

    • 嗯,似乎还是有问题。我已经添加了我的快速代码,包括你的函数。你会好心看看有什么问题吗?真的很感激!
    • 你给了吗,UIWebView 代表?
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2014-03-18
    • 1970-01-01
    • 2011-12-01
    相关资源
    最近更新 更多