首页 > 解决方案 > Swift - JSON 数据不会显示在 UITableview 中

问题描述

我正在尝试从服务器检索数据。我可以在控制台中显示我的数据。

我试图在 UITableview 中显示它,但没有任何反应。我试图创建一个本地 JSON 文件并且我能够显示它,但是当来自服务器时它不会工作。

let newUrl = URL(string: urlGetNotifications)
        let configuration = URLSessionConfiguration.default
        var session = URLSession.shared
        var request = URLRequest(url: newUrl!)

        session = URLSession(configuration: configuration)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue(authkeyFCM, forHTTPHeaderField: "auth-key")
        request.setValue(tokenFCM.string(forKey: "tokenFCM"), forHTTPHeaderField: "token")

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

                guard let j = newUrl
                    else{
                        print("data not found")
                        return
                }

                guard let d = try? Data(contentsOf: j)
                    else { print("failed")
                        return

                }

                guard let rootJSON = try? JSONSerialization.jsonObject(with: d, options: [])
                    else{ print("failedh")
                        return

                }
                if let data = data, let dataString = String(data: data, encoding: .utf8) {

                    if let JSON = rootJSON as? [String: Any] {

                        print("data: \(dataString)")
                        guard let jsonArray = JSON["data"] as? [[String: Any]] else {
                            return
                        }

                        print(jsonArray)
                        let name = jsonArray[0]["type"] as? String
                        print(name ?? "NA")
                        print(jsonArray.last!["created_at"] as? String as Any)

                        self.notificationList = jsonArray.compactMap{return NotificationData($0)}
                        self.tableView.reloadData()

                    }

                }
            }

        })
        task.resume()

标签: iosjsonswift

解决方案


我想到了

这个有效

 let newUrl = URL(string: urlGetNotifications)
        let configuration = URLSessionConfiguration.default
        var session = URLSession.shared
        var request = URLRequest(url: newUrl!)

        session = URLSession(configuration: configuration)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue(authkeyFCM, forHTTPHeaderField: "auth-key")
        request.setValue(tokenFCM.string(forKey: "tokenFCM"), forHTTPHeaderField: "token")

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

                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: [])
                    //self.showSpinner(onView: self.view)
                    print("The Response is : ",json)

                    if let data = data, let dataString = String(data: data, encoding: .utf8) {

                        if let JSON = json as? [String: Any] {

                            print("dumaan ba dito")
                            print("data: \(dataString)")
                            guard let jsonArray = JSON["data"] as? [[String: Any]] else {
                                return
                            }

                            print(jsonArray)
                            let name = jsonArray[0]["type"] as? String
                            print(name ?? "NA")
                            print(jsonArray.last!["created_at"] as? String as Any)

                            self.notificationList = jsonArray.compactMap{return NotificationData($0)}
                            self.tableView.reloadData()

                        }

                    }




                } catch {
                    print("JSON error: \(error.localizedDescription)")
                }


            } // end

        })
        task.resume()


推荐阅读