如何在服务器中将JSON数据放入Swift 3的表格视图单元格中

我试图从服务器显示JSON数据到表格视图单元格。 我在捕获响应值时遇到了问题。 如何获得jobTime.count并获得jobEndTime值? 我想为每个单元格显示jobTime-jobEndTime。

我想我必须声明一个自定义结构作业。 但我不知道如何创建。

struct Job {
    var jobDate: String
    var jobEndTime: Int
    var jobID: Int
    var jobTime: Int

    init(dict: [String:AnyObject]) {
        self.jobDate = dict["jobDate"] as! String
        self.jobEndTime = dict["jobEndTime"] as! Int
        self.jobID = dict["jobID"] as! Int
        self.jobTime = dict["jobTime"] as! Int
    }
}

var jobs = [Job]()
override func viewDidLoad() {
    super.viewDidLoad()
    retrieveTime()
}

func retrieveTime(){
    if let crew = user!["crew"] as? [String:Any], let crewID = crew["crew_id"] as? String{

        let param = ["action": "retrieve time", "job": ["crew_id": crewID, "jobDate": passedData]] as [String : Any]

        let headers = [
            "content-type": "application/json",
            "cache-control": "no-cache"
        ]

        if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {

            let request = NSMutableURLRequest(url: URL(string: "http://52.221.231.3/gv/app_api.php")!,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            request.httpMethod = "POST"
            request.allHTTPHeaderFields = headers
            request.httpBody = postData

            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                (data, response, error) -> Void in
                DispatchQueue.main.async(execute: {
                    if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
                    {
                        let result = json["result"] as? String

                        if (result == "success") {

                            if let jsonData = json["jobs"] as? [[String:AnyObject]] {
                                self.jobs = jsonData.map { Job(dict: $0) }
                            }
                                print(self.jobs)
                                self.tableView.reloadData()
                            }
                        }else{
                            print(result!)

                        }
                    }
                })
            }

            task.resume()
        }

    }

}

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "jobCell", for: indexPath)
    let job = self.jobs[indexPath.row]
    cell.textLabel?.text = job.jobDate

    return cell
}

对不起,这是凌乱的代码,这是我第一次在Swift中使用JSON。

JSON Data :

    {
    jobs = (
        {
            jobDate = "2017-09-07";
            jobEndTime = 1504749600;
            jobID = 104;
            jobTime = 1504746000;
        },
                {
            jobDate = "2017-09-07";
            jobEndTime = 1504756800;
            jobID = 105;
            jobTime = 1504753200;
        }
    );
    message = "Retrieve Sucessfully";
    result = success;
}
author: wan-jern
采纳答案:

作为一个建议,Alamofire是一个发送网络请求的好框架,可以在这里找到。

另外,为了使用JSON,Swift不太好。 你必须为它编写很多额外的代码。 用于处理JSON的流行库称为SwiftyJSON,它非常适合Alamofire,它可以在这里找到。

这将允许您使用JSON响应来编写请求,如下所示:

Alamofire.request(url, method: .get).validate().responseJSON { response in

    switch response.result {

    case .success(let value):

        let json = JSON(value)

        let name = json["name"].stringValue
        let job = json["teacher"].stringValue

    case .failure(let error):

        print(error)
    }
}

SwiftyJSON自述文件包含有关如何循环浏览JSON结果的信息,您需要这样做。

author: martheli

参考更多解答: How to put JSON data from server into table view cell in Swift 3 ,转载请保留出处如何在服务器中将JSON数据放入Swift 3的表格视图单元格中及作者信息

Statement: We respect knowledge and authors. Since the content comes from the Internet and is intended for scientific research, any reprinters should retain the author's signature and origin. If you are the author of the content and feel in dispute, please contact email: 1076545519@qq.com. We will find out the situation and deal with it in time. We sincerely thank the author for his hard work.


更多:json