ios - 将 JSON 从外部服务器连接到 Swift tableView

标签 ios json swift uitableview tableview

我是 Swift 新手,正在尝试创建一个从我的网站读取 JSON 数据的表。我遵循了一些教程,并且能够让我的代码与表 Controller 一起使用。现在我尝试使用内部带有 TableView 的 View Controller ,这样我就可以进行更多自定义。我的问题是,当我尝试使用新代码时,我无法实际显示数据。

这就是我的 viewController.swift 中的内容:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!
var TableData:Array< String > = Array < String >()


override func viewDidLoad() {
    super.viewDidLoad()

    get_data_from_url("http://www.stevenbunting.org/Alliris/service.php")
}



func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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


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

    cell.textLabel?.text = TableData[indexPath.row]

    return cell
}






func get_data_from_url(_ link:String)
{
    let url:URL = URL(string: link)!
    let session = URLSession.shared

    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "GET"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData


    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard let _:Data = data, let _:URLResponse = response  , error == nil else {

            return
        }


        self.extract_json(data!)


    })

    task.resume()

}


func extract_json(_ data: Data)
{


    let json: Any?

    do
    {
        json = try JSONSerialization.jsonObject(with: data, options: [])
    }
    catch
    {
        return
    }

    guard let data_list = json as? NSArray else
    {
        return
    }


    if let countries_list = json as? NSArray
    {
        for i in 0 ..< data_list.count
        {
            if let country_obj = countries_list[i] as? NSDictionary
            {
                if let country_name = country_obj["user"] as? String
                {
                    if let country_code = country_obj["friendlist"] as? String
                    {
                        TableData.append(country_name + " [" + country_code + "]")
                    }
                }
            }
        }
    }



    DispatchQueue.main.async(execute: {self.do_table_refresh()

    })

}

func do_table_refresh()
{
    self.tableView.reloadData()

}


}

最佳答案

可能你没有设置tableView的dataSource。为此,请实现 UITableViewDataSource-protocol在 ViewController 类中,并在 viewDidLoad() 中将 tableView 的 dataSource-property 设置为 self,例如:

class ViewController: UIViewController, UITableViewDataSource {
// ...
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        // ...
    } 
    //...
}

哦,不要忘记 Apple 传输安全设置,否则你将看不到任何内容,因为 iOS 不再允许 HTTP,你已经使用了 HTTPS。处理此问题的正确方法是为您的域获取 SSL 证书。

快速又肮脏且绝对不推荐的方法是 disable ATS or to set an exception for certain, trustworthy domains .

关于ios - 将 JSON 从外部服务器连接到 Swift tableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42843869/

相关文章:

ios - 访问制服的 SKShader 要求是什么?

javascript - 将数组添加到关联数组/对象

Swift 如何在 map View 上显示某人的位置?

ios - _webView didFinish 导航不起作用

swift - 使用 Swift 3 编写桥接类脚本

ios - 通知不触发

ios - 使用Sap Cloud Kit for iOS的Odata服务消耗

ios - 等待 block 完成

javascript - PHP 不解码使用 Javascript 创建的 JSON 对象。错误总是返回 4

java - 如何序列化 Jackson Joda 日期格式?