按下按钮时在webview中打开URL

时间:2017-04-30 12:17:19

标签: ios swift uiwebview

所以我有一个按钮,我试图用它作为一种方式让用户导航到一个特定的URL(它确实如此),但按钮是在safari中打开url,我希望它在我的网页视图中显示。

这是我的视图controller.swift文件:

@IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var myProgressView: UIProgressView!
    @IBOutlet weak var Home_button: UIButton!


    var theBool: Bool = false
    @IBOutlet weak var refresh_button: UIButton!
    @IBAction func go_home(_ sender: UIButton) {
        UIApplication.shared.openURL(NSURL(string:"my url")! as URL)
    }
    var myTimer = Timer()

    override func viewDidLoad() {


        super.viewDidLoad()
        webView.delegate = self

        myTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(webViewDidStartLoad(_:)), userInfo: nil, repeats: true)
        let websiteurl  = URL(string: "another url")
        let websiteurlrequest = URLRequest(url: websiteurl!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData,
                                           timeoutInterval: 10.0)

   webView.loadRequest(websiteurlrequest)


    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        //if let myProgressView.progress is not nil{
        myProgressView?.progress += 0.045
        //}

    }


    func webViewDidFinishLoad(_ webView: UIWebView) {
        let loadinglabel = self.view.viewWithTag(100)
        loadinglabel?.removeFromSuperview()
        myProgressView?.progress = 100
        myProgressView?.removeFromSuperview()

    }



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

    func go() {
        myProgressView?.progress += 0.005
    }
}

如何在按下按钮的Web视图中打开网址,而不是在Safari中打开网页?

提前致谢!

3 个答案:

答案 0 :(得分:1)

更改按钮操作方法,如下所示:

@IBAction func go_home(_ sender: UIButton) {
            webView.loadRequest(websiteurlrequest)
    }

并从viewDidLoad中删除webView.loadRequest(websiteurlrequest)方法。然后,当您点击按钮时,您的webView会加载内容。

答案 1 :(得分:1)

试试这个。应该在Swift 3中工作

@IBAction func go_home(_ sender: UIButton) {
yourWebView.loadRequest(URLRequest(url: URL(string: "http://www.google.com")!))
}

答案 2 :(得分:0)

将以下代码添加到按钮操作区域

self.openWebURL(url: webUrl)

加载网址的功能

func openWebURL(url : URL)
  {
    let safariVC = SFSafariViewController(url: url)
    present(safariVC, animated: true, completion: nil)
  }

SFSafariViewControllerDelegate应该像这样添加到类标题中

class YourClassName: UIViewController, SFSafariViewControllerDelegate 

希望这对您有帮助...