iosiphoneswiftswift4jsqmessagesviewcontroller

How to add user image in JSQMessageViewController Swift 4


I'm using JSQMessageViewController for my Chat Application. Tried a lot to set incoming and outgoing message users image. If anybody using this library , Please help me to set user images.

Thanks in advance.


Solution

  • You can have to variables of type "JSQMessagesAvatarImage" on your "JSQMessagesViewController" one for sender and one for reciever. Before presenting your "JSQMessagesViewController" you can assign the images to these to variables using the JSQAvatarImageFactory initializer method that takes a UIImage and size , like this :

    chatVc.senderImg = [JSQMessagesAvatarImageFactory avatarImageWithImage:senderImage diameter:80] 
    chatVc.receiverImg = [JSQMessagesAvatarImageFactory avatarImageWithImage:receiverImage diameter:80]
    

    than inside your "JSQMessagesViewController" in the dataSource method "avatarImageDataForItemAtIndexPath" you can return the sender or receiver avatar like this :

    - (id<JSQMessageAvatarImageDataSource>)collectionView:(JSQMessagesCollectionView *)collectionView avatarImageDataForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    JSQMessage *message = [self.messages objectAtIndex:indexPath.item];
    
    if ([message.senderId isEqualToString:self.senderId])
        return _senderImg;
    else
        return _receiverImg;}
    

    This code is in objective-C , I don't have it in swift but I believe you can convert it into swift easily.