【问题标题】:Connecting JSON from external server to Swift tableView将 JSON 从外部服务器连接到 Swift tableView
【发布时间】:2017-03-16 20:10:07
【问题描述】:

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

这就是我在 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()

}


}

【问题讨论】:

  • 你把ViewController设置为tableView的数据源了吗?可能不会,因为您的 ViewController 代码没有实现 UITableViewDataSource-protocol ;)

标签: ios json swift uitableview tableview


【解决方案1】:

可能你没有设置tableView的dataSource。为此,请在 ViewController-class 中实现 UITableViewDataSource-protocol,并在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多