TableView打开网址

时间:2019-03-17 07:53:16

标签: swift

我有代码可以加载从api https://api.myjson.com/bins/oe3gu返回的结果:

let url = URL(string:"https://api.myjson.com/bins/oe3gu")
        let task = URLSession.shared.dataTask(with: url!) {
            data, responese, error in

            if error != nil {
                print(error!)
            } else {
                if let dataContent = data {
                    do {
                        let result = try JSONSerialization.jsonObject(with: dataContent, options: JSONSerialization.ReadingOptions.mutableContainers)
                        print(result)

                    } catch {
                        print("Json Faild")
                    }
                }
            }
        }
        task.resume()

如何将标题放在tableView的单元格标签中,然后单击单元格时要在浏览器中打开

1 个答案:

答案 0 :(得分:0)

对TVCell使用常规代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: REUSE_ID, for: indexPath) as! TripTableViewCell

    // Configure the cell...        
    let row = indexPath.row
    // take a part fo url.. 
    let title = ...[row]
    cell.textLabel.text = title

....

您可以例如:

.. url = URL(string:“ https://api.myjson.com/bins/oe3gu”)

let title = url.lastPathComponent

如果“ oe3gu”足够了。

我会更喜欢:

TableViewController类:UITableViewController {

typealias InfoTuple = (String,String)

let myInfo :[InfoTuple] = [
    ("https://api.myjson.com/bins/oe3gu" , "link 1"),
    ("https://api.myjson.com/bins/oe3gu2" , "link 2"),
    ("https://api.myjson.com/bins/oe3gu2" , "link 3"),
]

override func viewDidLoad() {
    super.viewDidLoad()
}


// MARK: - Table view data source


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myInfo.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

    // Configure the cell...
    let row = indexPath.row
    let (title, _) = myInfo[row]
    cell.textLabel?.text = title
    return cell
}

....

,您的代码将是:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let row = indexPath.row
    let (_, url) = myInfo[row]

    let task = URLSession.shared.dataTask(with: url!) {
        data, responese, error in
        .....
}