简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM