我收到此API响应,需要将其加载到UITableView中:
{"count":2,"next":null,"previous":null,"results":[{"id":168,"contact":{"id":303,"avatar":null,"userId":249,"phone":"46528","rate":0.0,"firstName":"Jack","middleName":null,"lastName":null,"categories":[],"isContractor":false,"isIndividual":false,"isActive":true,"workspaceId":298,"workspaceTitle":"SomeAnotherCompany","workspaceLogo":null,"vatNumber":691102002},"contactId":303,"workspaceId":302,"isCustomer":false},{"id":169,"contact":{"id":348,"avatar":null,"userId":280,"phone":"+123123123","rate":0.0,"firstName":"Doe","middleName":null,"lastName":"John","categories":[{"id":221,"title":"IT Consulting","category":145,"workspaceCategory":434,"workspaceUser":348}],"isContractor":true,"isIndividual":false,"isActive":true,"workspaceId":342,"workspaceTitle":"ООО \"SomeCompany\"","workspaceLogo":null,"vatNumber":192532321},"contactId":348,"workspaceId":302,"isCustomer":false}]}
我正在尝试将这些值加载到单元格中: - 名字 -费率 -头像 - 电话 -WorkspaceTitle
,但标签显示为空白,否则我的应用崩溃。这是我的代码:
func getData() {
DispatchQueue.main.async {
let headers = [
"content-type" : "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"Authorization": "JWT \(access)"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://SomeApi.com")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
// request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
if let dataNew = data, let responseString = String(data: dataNew, encoding: .utf8) {
print(responseString)
let dict = self.convertToDictionary(text: responseString)
print(dict?["results"] as Any)
self.responseArray = (dict?["results"] as! NSArray) as! [PerformersViewController.JSONDictionary]
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
})
dataTask.resume()
}
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
请有人指出我的错误。这是我尝试将数据加载到单元格中的方式:
let getPeopleData = responseArray[indexPath.row]
cell.performerImage.image = getPeopleData["avatar"] as? UIImage
cell.performerNameLabel.text = getPeopleData["firstName"] as? String
cell.ratingLabel.text = String(getPeopleData["rate"] as? Int ?? 0)
cell.phoneNumberLabel.text = getPeopleData["phone"] as? String
cell.companyTitleLabel.text = getPeopleData["workspaceTitle"] as? String
return cell