我有以下两个功能:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath)
let message = self.messages[indexPath.row]
// Set table cell values
getUserFriendlyName(sid: message.sid!, arg: true, completion: { (success) -> Void in
cell.detailTextLabel?.text = self.friendly_name
cell.textLabel?.text = message.body
cell.selectionStyle = .none
//self.tableView.reloadData()
})
return cell
}
和
func getUserFriendlyName(sid: String, arg: Bool, completion: @escaping (Bool) -> ()) {
let ACCOUNT_IDENTITY: String = "AC***redacted"
let AUTH_TOKEN: String = "**redacted"
let SERVICE_ID: String = "IS***redacted"
let loginString = "\(ACCOUNT_IDENTITY):\(AUTH_TOKEN)"
let loginData = loginString.data(using: String.Encoding.utf8)
let base64LoginString = loginData!.base64EncodedString()
let url = URL(string: "https://chat.twilio.com/v2/Services/IS***redacted/Users/US***redacted")
var request = URLRequest(url: url!)
var session = URLSession.shared
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//request.addValue(AUTH_TOKEN, forHTTPHeaderField: "Authorization")
var fn: String!
let task = session.dataTask(with: request, completionHandler: { data, response, error in
var strData = String(data: data!, encoding: String.Encoding.utf8)
print("Body: \(strData)")
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
//getting the json response
print(json)
fn = json["friendly_name"] as! String?
self.friendly_name = fn
completion(arg)
//return fn
//print(fn)
})
task.resume()
}
这是我遇到的问题...当检测到新的聊天消息时,会调用tableView函数。使用文本和子文本创建新单元格。因为原生的Twilio代码不允许我显示谁写了聊天的友好名称,所以我必须去做一个HTTP调用,所以我调用getUserFriendlyName()。因为resumeTask()是异步的,所以程序的流程如下:
我尝试过的:
我开始相信我唯一的希望就是/Handler / userCompletionHandler。我已经和他们玩了很长时间并且无法获得理想的结果,这将是第一个传入的聊天消息填充了来自HTTP请求的数据。
有人可以帮忙吗?
收到消息时,请不要将其直接添加到消息数组中,而是先调用
// this goes inside some function not cellForRowAt
let message = // received
getUserFriendlyName(sid: message.sid!, arg: true, completion: { (success) -> Void in
message....// set all needed properties
self.messages.append(message)
self.tableview.reloadRows(at:[IndexPath(row:messages.count - 1,section:0)],with:.none)
}
不要在cellForRowAt
中进行任何异步工作,因为它将在每次滚动时完成,此外它不会同时显示完整数据
完成session.dataTask(with: request
是一个后台主题,所以考虑一下
DispatchQueue.main.async {
completion(arg)
}
你做self.friendly_name
self.friendly_name = fn
一个vc属性,它应该是每个消息对象的属性,以便不与其他消息发送者混合