Make Swift Button Hyperlink

I use quickly and since it is a fairly new programming language, there is not much documentation on it. I am trying to make a button act like a hyperlink. I created an IBAction, but I don't know where to go from there. Here is my code:

import UIKit

class ViewController: UIViewController {

    @IBAction func WebLink(sender: AnyObject) {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

}

      

+3


source to share


3 answers


You can open the url by calling a method openURL

on the UIApplication instance:



@IBAction func WebLink(sender: AnyObject) {
    if let url = NSURL(string: "http://...") {
        UIApplication.sharedApplication().openURL(url)
    }
}

      

+17


source


For Swift 3, openURL is deprecated.

Instead, there is open, which takes parameters and a completion handler:



sharedApplication () has also been replaced with a shared property.

if let url = URL(string: "https://...") {
    UIApplication.shared.open(url, options: [:]) {
        boolean in
        // do something with the boolean
    }
}

      

+1


source


The API is not available below iOS 10, so the following needs to be added.

guard let url = URL(string: "https://www.google.com/") else {
    return
}
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:]) {_ in }
} else {
    // Fallback on earlier versions
    UIApplication.shared.openURL(url)
}

      

0


source







All Articles