简体   繁体   中英

iOS Swift - How to get the last items of an array and append it to another array for chat messages

I have the following code (a Parse Server query into a function that gets fired every 20 seconds and checks if there are new rows in the Messages class (table)):

    /* Variables */
    var messagesArray = [PFObject]()
    var theMessages = [PFObject]()


    /* func queryMessages() code */
    let messId1 = "\(currentUser.objectId!)\(userObj.objectId!)"
    let messId2 = "\(userObj.objectId!)\(currentUser.objectId!)"

    let predicate = NSPredicate(format:"messageID = '\(messId1)' OR messageID = '\(messId2)'")
    let query = PFQuery(className: MESSAGES_CLASS_NAME, predicate: predicate)

    query.whereKey(MESSAGES_DELETED_BY, notContainedIn: [currentUser.objectId!])
    query.order(byAscending: "createdAt")
    query.skip = skip
    query.findObjectsInBackground { (objects, error)-> Void in
        if error == nil {
            for i in 0..<objects!.count { self.messagesArray.append(objects![i]) }
            if (objects!.count == 100) {
                self.skip = self.skip + 100
                self.queryMessages()
            } else {
                self.messagesArray = objects!


                /*test*/
                let messDiff = self.messagesArray.count - self.theMessages.count
                print("MESSAGES ARRAY: \(self.messagesArray.count)")
                print("THE MESSAGES: \(self.theMessages.count)")
                print("MESS DIFF: \(messDiff)\n")

                if self.theMessages.count < self.messagesArray.count {
                    for i in 0..<messDiff {
                        self.theMessages.append(self.messagesArray[i])
                    }// ./ For
                    self.messagesTableView.reloadData()
                }// ./ If

                // Scroll TableView down to the bottom
                if objects!.count != 0 {
                    Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.scrollTableViewToBottom), userInfo: nil, repeats: false)
                }
            }// ./ If

        // error
        } else { self.simpleAlert("\(error!.localizedDescription)")
    }}

So, the app is running on my device, and with another device I send 2 new messages to the test User on my device. After 20 seconds, a Timer calls the function above and I obviously get this in the console:

MESSAGES ARRAY: 9
THE MESSAGES: 7
MESS DIFF: 2

So, what I would need is to simply append the 2 new items of the messagesArray into the theMessages array, so that when my TableView will reload, it'll just add 2 new rows on its bottom.

Obviously now I get the first 2 messages again because of this code:

for i in 0..<messDiff {
    self.theMessages.append(self.messagesArray[i])
}// ./ For

I cannot figure out what 'workaround' I should use to achieve what I need...

As you are reloading the entire table view without animations anyway why not simply

self.theMessages = self.messagesArray
self.messagesTableView.reloadData()

Or if the new messages are reliably at the end of the array get them with suffix and append them to theMessages

let newMessages = Array(self.messagesArray.suffix(messDiff))
self.theMessages.append(contentsOf: newMessages)
if self.theMessages.count < self.messagesArray.count {
                let temp = self.theMessages.count
                for i in 0..<messDiff {
                    self.theMessages.append(self.messagesArray[i+temp])
                }// ./ For
                self.messagesTableView.reloadData()}

change your code reload data code to this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM