我正在使用post方法在表格视图中显示数据。我得到了我的json响应。但我无法在表视图中仅显示可见的nil值显示我的数组数据,并且调试区域也显示此值= [“ fav”:<__ nsarraym>()]为什么我要获取阵列数据?我的代码有什么错误?
let parameters = ["userid": 1, "start": "0"] as [String : Any]
//create the url with URL
let url = URL(string: "https://test.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print ("data = \(json)")
if let arry = json["pnbu"] as? [[String:Any]] {
for dic in arry {
let buzzyuser_id = dic["buzzyuser_id"]
let buzzyuser_location = dic["buzzyuser_location"]
let buzzyuser_image = dic["buzzyuser_image"]
self.favs.append(JsonResponse(buzzyuser_id: buzzyuser_id as? String, buzzyuser_location: buzzyuser_location as? String, buzzyuser_image: buzzyuser_image as? String))
print(buzzyuser_id!)
DispatchQueue.main.async { // Correct
self.TableSectionView.reloadData() }
}
}
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
show array list in debug area but my data can't response in my tableview. after run simulator thread 1 error in debug area...
but get method code will works fine.
为了给出这个答案,我对其余的应用程序做了一些假设,因为没有提供细节。这些包括:
arry
数组鉴于这些警告,我将按照以下内容重新组织代码,以确保在调用.reloadData()
之前视图控制器具有完整的数据集>
//replacing for loop in example code above
let results = [JsonResponse]()
for dic in arry {
let buzzyuser_id = dic["buzzyuser_id"]
let buzzyuser_location = dic["buzzyuser_location"]
let buzzyuser_image = dic["buzzyuser_image"]
results.append(JsonResponse(buzzyuser_id: buzzyuser_id as? String,
buzzyuser_location: buzzyuser_location as? String,
buzzyuser_image: buzzyuser_image as? String))
}
DispatchQueue.main.async {
self.favs = results
self.tableView.reloadData()
}