我有一个需要返回参数的函数:
override func collectionView(collectionView: JSQMessagesCollectionView!,
avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! { ... }
所以它需要JSQMessageAvatarImageDataSource
这个。当我尝试:
self.downloadAvatar(OneChat.sharedInstance.fetchVCardOfOtherUserBy((OneChat.sharedInstance.xmppStream?.myJID)!).avatarURL, completion: { (image) in
return JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: 30)
})
其中:
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)
}
})
}
它没有看到我在completionHandler中返回并给出了这个错误:
Missing return in a function expected to return 'JSQMessageAvatarImageDataSource!'
我该如何解决?
答案 0 :(得分:0)
这是因为:
1)完成处理程序以异步方式执行
2)return语句是指从闭包返回值,而不是avatarImageDataForItemAtIndexPath
函数
您需要一种不同的方法。下载头像,然后将其设置到集合视图单元格。不要试图从函数返回它,因为在执行函数时你还没有它。
对每个集合视图单元执行downloadAvatar
操作。您需要将单元格传递到该范围,以便闭包可以保留它。下载头像后,只需将其设置为单元格
类似的东西:
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
}
})
}