如何在Swift 3中获取JSON来填充UITableView?

编程入门 行业动态 更新时间:2024-10-28 00:18:15
本文介绍了如何在Swift 3中获取JSON来填充UITableView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我无法显示数据.我已经从MCViewController自定义类发布了我的代码.它不会建立.但是我确实在控制台中得到了数据响应.有人可以向我指出我做错了什么吗?

I am having trouble getting data to display. I have posted my code from the MCViewController custom class. It won't build. However I do get data response in the console. Can someone point out to me what I did wrong?

class MCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let message_url = "www.testing/api/resources/get_film_message/film_id/3825" let send_url = "www.testing/api/resources/send_film_message" let film_id = "3825" var messageArray = [String]() weak var messageView : UITableView! func messageView(_ messageView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageArray.count } func messageView(_ messageView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = messageView.dequeueReusableCell(withIdentifier: "msgContent", for:indexPath) as! MessageTableViewCell // Configuring Cell cell.msgContent.text = messageArray[indexPath.row] // Returning the cell return cell } @IBOutlet weak var MessageInput: UITextField! @IBAction func Sendmsg(_ sender: Any) { Sendmsg(username:MessageInput.text!, password: film_id) } override func viewDidLoad() { super.viewDidLoad() messageView.dataSource = self messageView.delegate = self // Do any additional setup after loading the view. //let post_data: NSDictionary = NSMutableDictionary() // post_data.setValue(username, forKey: "username") // post_data.setValue(password, forKey: "password") let url:URL = URL(string: message_url)! let session = URLSession.shared let request = NSMutableURLRequest(url: url) request.httpMethod = "GET" request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY") request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization") request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData // Do any additional setup after loading the view. var paramString = "" // for (key, value) in post_data // { // paramString = paramString + (key as! String) + "=" + (value as! String) + "&" // } // request.httpBody = paramString.data(using: String.Encoding.utf8) let task = session.dataTask(with: request as URLRequest, completionHandler: { ( data, response, error) in guard let _:Data = data, let _:URLResponse = response , error == nil else { return } let json: Any? do { json = try JSONSerialization.jsonObject(with: data!, options: []) if let parsedData = json as? [[String:Any]] { for dict in parsedData { if let title = dict["message"] as? String { self.messageArray.append(title) print(json) } } } } catch { return } guard let server_response = json as? NSDictionary else { return } if let data_block = server_response["data"] as? NSDictionary { if let session_data = data_block["session"] as? String { // self.login_session = session_data let preferences = UserDefaults.standard preferences.set(session_data, forKey: "session") // DispatchQueue.main.async(execute: self.LoginDone) } } }) task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func Sendmsg(username:String, password:String) { let post_data: NSDictionary = NSMutableDictionary() post_data.setValue(username, forKey: "message") post_data.setValue(password, forKey: "film_id") let url:URL = URL(string: send_url)! let session = URLSession.shared let request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY") request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization") request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData var paramString = "" for (key, value) in post_data { paramString = paramString + (key as! String) + "=" + (value as! String) + "&" } request.httpBody = paramString.data(using: String.Encoding.utf8) let task = session.dataTask(with: request as URLRequest, completionHandler: { ( data, response, error) in guard let _:Data = data, let _:URLResponse = response , error == nil else { return } let json: Any? do { json = try JSONSerialization.jsonObject(with: data!, options: []) print(json) } catch { return } guard let server_response = json as? NSDictionary else { return } // if let data_block = server_response["data"] as? NSDictionary // { // if let session_data = data_block["session"] as? String // { // self.login_session = session_data // // let preferences = UserDefaults.standard // preferences.set(session_data, forKey: "session") // // DispatchQueue.main.async(execute: self.LoginDone) // } // } // }) task.resume() }

推荐答案

在viewDidLoad()中,将{}捕获到{}附加到messageArray的位置,像这样调用messageView.reloadData():

In viewDidLoad(), the do {} catch {} where you append to messageArray, call the messageView.reloadData() like this:

do { json = try JSONSerialization.jsonObject(with: data!, options: []) if let parsedData = json as? [[String:Any]] { for dict in parsedData { if let title = dict["message"] as? String { self.messageArray.append(title) print(json) } } } messageView.reloadData() // this is your tableView reload } catch { return }

通常,人们将其UITableView对象称为tableView,以使其更容易发现代码.但是,没有人禁止您使用messageView作为tableView的名称.

Usually people will call their UITableView object as tableView, to make it easier to spot in the code. Nobody prohibit you to use messageView as the name of your tableView, though.

更多推荐

如何在Swift 3中获取JSON来填充UITableView?

本文发布于:2023-08-05 21:41:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1308223.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Swift   UITableView   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!