I am pretty new to completion handlers, thats why I am asking this. I need to have a working completion handler so that the image gets the data of the firebase database, before it is returned. This is the code snippet.
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
let message = messages[indexPath.item]
var profileImage: UIImage!
if message.senderUID == currentUser.uid {
return nil
} else {
setAvatarImages(message.senderUID, Image: profileImage, completion: { (error) in
print("done")
})
return JSQMessagesAvatarImageFactory.avatarImage(with: profileImage, diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
}
}
func setAvatarImages(_ UID: String!, Image: UIImage!, completion: @escaping (NSError?) -> Void) {
var Image = Image
let ref = DatabaseReference.users(uid: UID).reference()
ref.observeSingleEvent(of: .value, with: { (snapshot) in
let user = User(dictionary: snapshot.value as! [String : Any])
print("done")
user.downloadProfilePicture(completion: { (image, error) in
if image != nil {
Image = image
} else if error != nil {
print(error?.localizedDescription ?? "")
}
})
})
}
The problem is, that the setAvatarImages function is not executed how it should be, instead the return is called immediately and gives back an image which has the value of nil, which leads to a fatal error. Every help is appreciated!