Nate Grant Nate Grant - 6 months ago 144
Swift Question

tableviewcell open url on click swift

I've been trying to make a url open when I click a cell in my tableview programatticaly without having to make a webview controller and mess with seques. Any help on how I can get this accomplished. Below is the code I've tried

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {



if indexPath.row == 0 {
NSURL(string: "App Store Link")!
}
else if indexPath.row == 1 {
NSURL(string: "Send Us Feedback - Contact On Website")!
} else if indexPath.row == 2 {
NSURL(string: "https://www.instagram.com/prs_app/")!
} else if indexPath.row == 3 {
NSURL(string: "Snapchat")!
}

}


I appreciate the help. Thanks

Answer

You are looking for

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

this will open the safari browser for you

edit explanation for question in comment
It is better if you'll add enums or other constants, but this will do:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let url : NSURL?

    switch indexPath.section{
    case 0:
        switch indexPath.row{
        case 0:
            url = NSURL(string: "http://section0.row0.com")
        case 1:
            url = NSURL(string: "http://section0.row1.com")
        default:
            return;
        }

    case 1:
        switch indexPath.row{
        case 0:
            url = NSURL(string: "http://section1.row0.com")
        case 1:
            url = NSURL(string: "http://section1.row1.com")
        default:
            return;
        }
    default:
        return;
    }

    if url != nil{
        UIApplication.sharedApplication().openURL(url!)
    }
}
Comments