Я создаю приложение, в которое пользователи будут отправлять сообщения.У меня работает мессенджер, но внешний интерфейс не обновляется сразу после ввода нового комментария.Вы должны отступить, а затем вернуться, чтобы он появился.
Я исследовал примеры и получил код из курса, который я взял на udemy.Я пытался с tableview.reload () и tableview.insertrows ().Я отправляю данные с использованием JSON в PHP и MySQL.Он сразу отображается в БД, но мой код сначала обновляет интерфейс, но он просто не работает.
let messagetext = replyTxt.text.trimmingCharacters (in: .whitespacesAndNewlines)
hhmessages.insert(messagetext as AnyObject, at: hhmessages.endIndex)
let indexPath = IndexPath(row: self.hhmessages.count - 1, section: 0)
// update tableView
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
// scroll to the bottom
tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
// empty textView and reload it
replyTxt.text = ""
textViewDidChange(replyTxt)
let recipient = messages["username"] as! String
let rid = String(describing: messages["recipient_id"]!)
let uuid = messages["uuid"] as! String
puuid = UUID().uuidString
// prepare request
let url = URL(string: "http://localhost/messagepost.php")!
let body = "sender_id=\(user_id)&sender=\(username)&text=\(messagetext)&recipient_id=\(rid)&recipient=\(recipient)&uuid=\(uuid)&puuid=\(puuid)"
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = body.data(using: .utf8)
Код должен немедленно обновить UITableView с последним комментарием, а затем зафиксировать в базе данных.Я пытался в течение двух дней без удачи.Приветствуется любая помощь.
ОБНОВЛЕНИЕ С КОДОМ СТОЛОВЫХ ИСТОЧНИКОВ
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hhmessages.count
}
// Return cell to display on the tableView
// How many sections. Means numberOfSections * rows = view
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let colorSmoothGray = UIColor(red: 229/255, green: 229/255, blue: 234/255, alpha: 1)
let colorBrandBlue = UIColor(red: 148 / 255, green: 33 / 255, blue: 147 / 255, alpha: 1)
let pictureURL = hhmessages[indexPath.row]["uploadpath"] as? String
// no picture in the post
if pictureURL?.isEmpty == true {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ConversationCell
cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi));
isLoading = true
let hhpost = hhmessages[indexPath.row]
let smimages = hhpost["path"] as? UIImage
let text = hhmessages[indexPath.row]["messagetext"] as! String
cell.messageLbl.text = text
cell.smavaImg.image = smimages
cell.messageLbl.textAlignment = .right
cell.messageLbl.backgroundColor = colorSmoothGray
cell.messageLbl.textColor = .black
cell.messageLbl.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
cell.messageLbl.font?.withSize(25)
cell.messageLbl.clipsToBounds = true
// get main queue to this block of code to communicate back
DispatchQueue.main.async {
cell.messageLbl.sizeToFit()
tableView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)
cell.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "PicCell", for: indexPath) as! PicConversationCell
cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi));
cell.smavaImg.image = smimages
//if let message = messageData {
for i in 0 ..< self.incoming.count {
// Confiture the constraints for cell
if self.incoming[indexPath.row] == 1 {
// Constraints
cell.lefBubbleConstraint.isActive = true
cell.rightBubbleConstraint.isActive = false
if cell.postpictureImg.image == nil {
cell.postpictureImg.backgroundColor = colorwhite
cell.postpictureImg.clipsToBounds = true
}
else {
cell.postpictureImg.backgroundColor = .clear
cell.postpictureImg.clipsToBounds = true
}
}
else if self.incoming[indexPath.row] == 0 {
// Constraints
cell.lefBubbleConstraint.isActive = false
cell.rightBubbleConstraint.isActive = true
if cell.postpictureImg.image == nil {
cell.postpictureImg.backgroundColor = colorwhite
cell.postpictureImg.clipsToBounds = true
}
else {
cell.postpictureImg.backgroundColor = .clear
cell.postpictureImg.clipsToBounds = true
}
}
// pictures logic
let pictureString = hhmessages[indexPath.row]["uploadpath"] as? String
let pictureURL = URL(string: pictureString!)!
// if there are still pictures to be loaded
if hhmessages.count != pictures.count {
URLSession(configuration: .default).dataTask(with: pictureURL) { (data, response, error) in
// downloaded
if let image = UIImage(data: data!) {
self.pictures.append(image)
DispatchQueue.main.async {
cell.postpictureImg.image = image
}
}
}.resume()
// cached picture
} else {
DispatchQueue.main.async {
cell.postpictureImg.image = self.pictures[indexPath.row]
}
}
}
return cell
}
}