Happiehappie
Happiehappie

Reputation: 1074

How to load images asynchronously

Currently this is my implementation in a method in viewDidLoad dateParameter = self.lastMessageDate

        for chat in self.realm.objects(ChatObject).filter("room_id == \(self.room.id)").sorted("dateTime", ascending: true) {

            if chat.type == "GIFT" {
                print(chat.gift)
                let imageData = NSData(contentsOfURL: NSURL(string: chat.gift!.image)!)
                //let photoItem = JSQPhotoMediaItem(image: UIImage(data: imageData!))
                let photoItem = ChatImageJSQPhoto(image: UIImage(data: imageData!))

                let photoMessage = JSQMessage(senderId: String(chat.sender!.id), senderDisplayName: chat.sender!.username, date: self.formatter.dateFromString(chat.dateTime), media: photoItem)
                self.messages.append(photoMessage)
                //then get the message if it exists
                if chat.desc.characters.count > 0 {
                    self.addMessage(String(chat.sender!.id), senderName: chat.sender!.username, text: chat.desc, date: chat.dateTime)
                }
            } else {
                if chat.desc.characters.count > 0 {
                    print(chat.sender?.username)
                    self.addMessage(String(chat.sender!.id), senderName: chat.sender!.username, text: chat.desc, date: chat.dateTime)
                }
            }
        }
        self.finishReceivingMessage()

However, as you may have predicted, I will be stucked for a few seconds before going into my JSQMessagesViewController. How do I load at those bubbles and have an activity indicator in the middle of the bubble then load the images asynchronously?

Upvotes: 2

Views: 588

Answers (1)

Enea Dume
Enea Dume

Reputation: 3232

i prefer using kingfisher. trust me it's great

        let resource = ImageResource(downloadURL:URL(string: productsForSearch.result[indexPath.row].image_url )!,cacheKey: productsForSearch.result[indexPath.row].image_url )
        CollectionCell.imagesForSearch.kf.indicatorType = .activity //this is to make activity indicator
        CollectionCell.imagesForSearch.kf.setImage(with: resource)

Upvotes: 1

Related Questions