Search code examples
iosswiftuiwebview

open url in webview when button is pressed


So I've got a button which I'm trying to use as a means for the user to navigate to a specific URL (which it does), however the button is opening the url in safari, and i want it to be presented in my web view.

Here is my view controller.swift file:

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

How do I open the url in the web view on the button press, rather than in safari?

Thanks in advance!


Solution

  • Try this. Should work in Swift 3

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