0

I am trying to retrieve the data set in an array in one function, in a different function. I appended the data i want into the OtherUserArray in the createNewConversation function. However when i try the retrieve this data in the sendMessage function, it prints an empty array.

import MessageKit
import InputBarAccessoryView
import FirebaseAuth
import Firebase
import Foundation


final class DatabaseManager {

static let shared = DatabaseManager()

var foundOtherUser:String?

var OtherUserArray = [String]()

}

extension DatabaseManager {

// create a new conversation with target user, uid and first sent message
public func createNewConversation(with otherUserUid: String, name: String, firstMessage: Message, completion: @escaping(Bool) -> Void) {
    
    let db = Firestore.firestore()
    let CurrentUser = Auth.auth().currentUser?.uid
    let defaults = UserDefaults.standard
    defaults.set(CurrentUser, forKey: "uid")
    
    guard let currentUid = UserDefaults.standard.string(forKey: "uid"), let currentName = UserDefaults.standard.string(forKey: "usersFullname") else {
        return
    }
   
    let messageDate = firstMessage.sentDate
    
    let dateString = MessageViewController.dateFormatter.string(from: messageDate)
    
    var message = ""
    
    let conversationId = firstMessage.messageId
    
    let newConversationData: [String:Any] = [
    "id": conversationId,
    "other_user-uid": otherUserUid,
        "name": name,
    "latest-message": [
        "date": dateString,
        "message": message,
        "is-read": false
      ]
    ]
    
    // save other user uid to global var
    
    OtherUserArray.append(otherUserUid)

    }
}
}

 public func sendMessage(to conversation: String, name: String, newMessage: Message, completion: @escaping(Bool) -> Void) {
    
    // update the latest message
    print(self.OtherUserArray)

}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

1

The problem is not where you access self.OtherUserArray, but when you access it.

Data is loaded from Firebase asynchronously, while the rest of you code typically runs synchronously. By the time the print(self.OtherUserArray) in your sendMessage runs, the OtherUserArray.append(otherUserUid) hasn't been executed yet, so the array in empty. You can most easily verify this by running the code in a debugger and setting breakpoints on those like, or by adding print statements and checking the order of their output.

For examples of this, as well as how to solve the problem, see these previous questions:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807