Trying to create a tabbed application in swift with tableviewcells that launch Links in SafariViewController

Viewed 52

I am extremely new, followed the getting started guide for swift on Apples site.

I am trying to create a Tabbed App, each tab being a price range of gifts, and each gift being a tableviewcell with its own image and label. I also want to be able to click on the tableviewcell to open SFSafariViewController with a link directly to that gift online.

So far I have been able to create the tabbed application, create the table views and cells for each tab as static lists, setup the tableviewcells with images and labels, but I am stumped as to how to make it so that clicking on each tableviewcell opens a URL in the app.

Just looking to see if there’s anyone who has done something similar or could help me out. So far I have done almost all of it in storyboard, and if a storyboard solution exists that would be amazing. If not, any help at all would be great. Thank you!

1 Answers

What you want to do is make use of tableView:didSelectRowAtIndexPath:. This is a UITableViewDelegate method that is called anytime a cell is clicked. What you could do is check the IndexPath.row of the cell selected, and create an instance of SFSafariViewController that opens the corresponding URL:

import SafariServices
import UIKit

class YourViewController: UITableViewController {

    ...

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var controller: SFSafariViewController!
        switch indexPath.row {
        case 0:
            let url = URL(string: "www.website1.com")!
            controller = SFSafariViewController(url: url)
        case 1:
            let url = URL(string: "www.website2.com")!
            controller = SFSafariViewController(url: url)
        default:
            break
        }
        present(controller, animated: true, completion: nil)
    }
}
Related