Jason.Ma Jason.Ma - 1 month ago 8
iOS Question

Passing data from a tableview to webview

I am new of the swift3. So, please forgive me if you think it is easy question. Do not have a clear idea when searching internet or stack overflow with my situation, so I ask this question.

Goal: Passing data from a tableview to webview

Example: data 1,2,3... in the table, press 1, then jump into webview with value 1

Information:


  • In main.storyboard, looks like:

    main.storyboard

  • class oneViewController for a view controller with tableview

  • class twoViewController for a view controller with webview



In oneViewController, things are well set and select row at:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Array[indexPath.row] //This value expected to pass
//some code to execute passing data...
//Also, jump into another view controller with webview
}


In twoViewController, everything got ready:

//let passData = some code to get the data....
let URL = NSURL(string: "https://www.example.com?data=\(passData)")

webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)


Finally, PHP can get the value

echo $_GET["data"];


Questions:


  1. How to set the relationship between tableview and webview in main.storyblard?



Connect view controller to anther view controller? Or connect Table view Cell to view controller? Or something else.....


  1. How to implement passing data in class oneViewController and twoViewController?


Answer

Follow the below steps:-

Step 1: Below code will launch and pass the data in your TwoViewController. Please note that in your Main.Storyboard->TwoViewContoller, give the identifier as TwoViewController

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let storyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let twoVC:TwoViewController = storyBoard.instantiateViewController(withIdentifier: "TwoViewController") as! TwoViewController
    twoVC.passData = Array[indexPath.row]
    self.present(twoVC, animated: true, completion: nil)
}  

Step 2: In your TwoViewController class define a variable as below

var passData: String = ""