如何在 Swift 3 中使用 JSON 填充 TableView

Posted

技术标签:

【中文标题】如何在 Swift 3 中使用 JSON 填充 TableView【英文标题】:How to populate TableView with jSON in Swift 3 【发布时间】:2017-02-03 23:56:57 【问题描述】:

对不起,伙计们,我又老了。我正在伸出援手,因为我需要第二个 tableView 的帮助,我想在另一个视图控制器中实现。我基本上从另一个实际工作的 tableView 控制器复制了这段代码。所以我不确定我在哪里搞砸了,但我真的很感谢你的帮助。

class MCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate 

    let message_url = "https://www.distribber.com/api/resources/get_film_message/film_id/3825"
    let send_url = "https://www.distribber.com/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) -> MessageTableViewCell 
        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)

                        
                    
                    OperationQueue.main.addOperation(
                        self.messageView.reloadData()
                    )
                
            
            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()


    


    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     
     */


【问题讨论】:

问题出在哪里?视图没有填充还是没有正确解析? @Prientus 你知道我做错了什么吗? @MacStation 说 'MCViewController' 不符合协议 'UITableViewDataSource' 并且它不会构建 【参考方案1】:

您正在实现 UITableViewDataSource 但没有实现它所需的方法。

func tableView(UITableView, cellForRowAt: IndexPath)

func numberOfSections(in: UITableView)

实现这两个,不符合协议的错误应该消失。

【讨论】:

以上是关于如何在 Swift 3 中使用 JSON 填充 TableView的主要内容,如果未能解决你的问题,请参考以下文章

如何让 json 在 Swift 3 中填充 UITableView?

从 Swift 中的 Json 响应中填充 TableSection

IOS swift如何使用返回的Json数据填充我的TableView

从 Firebase 下载 json 并填充 TableView Swift 3

如何在 Swift 2 中从 JSON 填充我的 tableView?

在 Swift 中使用远程 JSON 数据填充 tableView