-1

I have a function which requires return parameter:

override func collectionView(collectionView: JSQMessagesCollectionView!, 
avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! { ... }

So it requires JSQMessageAvatarImageDataSource this. When I try to:

self.downloadAvatar(OneChat.sharedInstance.fetchVCardOfOtherUserBy((OneChat.sharedInstance.xmppStream?.myJID)!).avatarURL, completion: { (image) in
            return JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: 30)
        })

where:

private func downloadAvatar(URL: String, completion: (image: UIImage) -> Void) {
    let manager = SDWebImageManager.sharedManager()

    manager.downloadWithURL(NSURL(string: URL), options: .RefreshCached, progress: nil, completed: { (image: UIImage!, error: NSError!, imageCache: SDImageCacheType!, finished: Bool) in
        if (image != nil) {
            completion(image: image)
        }
    })
}

it does not see my return inside of completionHandler and gives me this error:

Missing return in a function expected to return 'JSQMessageAvatarImageDataSource!'

How can I fix that?

Doe
  • 431
  • 1
  • 8
  • 16

1 Answers1

0

this is because:

1) Completion handler is executed asynchronously

2) return statement refers to returning value from the closure, not avatarImageDataForItemAtIndexPath function

You need a different approach. Download avatar and then set it onto the collection view cell. Do not try to return it from function as you don't have it by the time the function is executed.

Perform downloadAvatar action for every collection view cell. You will need to pass the cell into that scope so the closure could retain it. Once the avatar is downloaded just set it to the cell

Something like:

private func downloadAvatar(URL: String, cell: YourCollectionViewCell) {
let manager = SDWebImageManager.sharedManager()

manager.downloadWithURL(NSURL(string: URL), options: .RefreshCached, progress: nil, completed: { (image: UIImage!, error: NSError!, imageCache: SDImageCacheType!, finished: Bool) in
    if (image != nil) {
        cell.avatar = image
    }
})
}
Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161