Дождитесь завершения другой функции внутри функции MessageKit - PullRequest
0 голосов
/ 04 марта 2019

Благодаря людям, которые помогли мне в моем другом вопросе SA, я смог создать функцию, которая возвращает логическое значение, чтобы видеть, голосовал ли уже пользователь в сообщении чата.Я хочу напечатать, если человек проголосовал в сообщении чата, используя функцию MessageKit messageBottomLabelAttributedText.Однако я не могу использовать возвращенное логическое значение для печати правильного текста.

Вот моя текущая функция messageBottomLabelAttributedText в MessagesDataSource:

    func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {

        var bool = didAlreadyVote(message: message as! MessageType){_ in Bool.self}

        if bool as? Bool == true {
            let dateString = self.formatter.string(from: message.sentDate)
            let likeString = "Voted"
            return NSAttributedString(string: "\(dateString) | \(likeString)", attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
        } else {
            let dateString = self.formatter.string(from: message.sentDate)
            return NSAttributedString(string: dateString, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
        }
    }
}

Для справки, вот функция didAlreadyVote этого сообществавыручил меня раньше:

func didAlreadyVote(message: MessageType, completion: @escaping (Bool) -> Void) {

    // check user votes collection to see if current message matches
    guard let currentUser = Auth.auth().currentUser else {return}
    let userID = currentUser.uid
    let docRef = Firestore.firestore().collection("users").document(userID).collection("upvotes").whereField("messageId", isEqualTo: message.messageId)

    docRef.getDocuments { querySnapshot, error in

        if let error = error {
            print("Error getting documents: \(error)")
            completion(false)
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                completion(true) /// Note that this will get called multiple times if you have more the one document!
            }
        }
    }
}

Когда я запускаю приложение, переменная bool ничего не возвращает.Как я могу получить логическое значение из функции и затем использовать его в messageBottomLabelAttributedText?

Спасибо!

1 Ответ

0 голосов
/ 04 марта 2019

Не ждите.

didAlreadyVote не не возвращает ничего.Он содержит обработчик асинхронного завершения, который передает значение Bool в качестве параметра.

Синтаксис

    didAlreadyVote(message: message){ boolValue in   
        if boolValue {
            let dateString = self.formatter.string(from: message.sentDate)
            let likeString = "Voted"
            return NSAttributedString(string: "\(dateString) | \(likeString)", attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
        } else {
            let dateString = self.formatter.string(from: message.sentDate)
            return NSAttributedString(string: dateString, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
        }

, но вы все равно не можете использовать его в messageBottomLabelAttributedText, потому что вы можете 'не возвращает ничего, если вы не внедрили также обработчик завершения, например

func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath, completion: @escaping (NSAttributedString) -> Void) {
    didAlreadyVote(message: message){ boolValue in   
        if boolValue {
            let dateString = self.formatter.string(from: message.sentDate)
            let likeString = "Voted"
            completion(NSAttributedString(string: "\(dateString) | \(likeString)", attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)]))
        } else {
            let dateString = self.formatter.string(from: message.sentDate)
            completion(NSAttributedString(string: dateString, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)]))
        }
    }
}
...