我想在我的条形按钮项目图像中显示当前用户的个人资料图片。将显示默认图片,但不显示用户的个人资料图片。
条形按钮图像的声明:
lazy var leftButton: UIBarButtonItem = {
var image = UIImage.init(named: "icons8-kontakte-50")?.withRenderingMode(.alwaysOriginal)
let button = UIBarButtonItem.init(image: image, style: .plain, target: self, action: #selector(ConversationViewController.showProfile))
return button
}()
在这里,我观察当前用户并获取当前个人资料图片:
//left bar button image fetching
self.navigationItem.leftBarButtonItem = self.leftButton
self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)
UserApi.shared.observeCurrentUser { (currentUser) in
self.currentUser = currentUser
guard let url = URL(string: currentUser.profilImageUrl!) else { return }
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error == nil {
let image = UIImage.init(data: data!)
let contentSize = CGSize.init(width: 30, height: 30)
UIGraphicsBeginImageContextWithOptions(contentSize, false, 0.0)
let _ = UIBezierPath.init(roundedRect: CGRect.init(origin: CGPoint.zero, size: contentSize), cornerRadius: 14).addClip()
image!.draw(in: CGRect(origin: CGPoint.zero, size: contentSize))
let path = UIBezierPath.init(roundedRect: CGRect.init(origin: CGPoint.zero, size: contentSize), cornerRadius: 14)
path.lineWidth = 2
UIColor.white.setStroke()
path.stroke()
let finalImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!.withRenderingMode(.alwaysOriginal)
UIGraphicsEndImageContext()
self.leftButton.image = finalImage
}
})
在此先感谢您的帮助!
答案 0 :(得分:2)
可以在任何线程上调用数据任务完成块,但是UI更新必须在主线程上完成。您需要分派回主线程来更新UIBarButtonItem
。
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil, let data = data, let image = UIImage(data: data) else { return }
let size = CGSize(width: 30, height: 30)
let rect = CGRect(origin: .zero, size: size)
let finalImage = UIGraphicsImageRenderer(size: size).image { _ in
let path = UIBezierPath(ovalIn: rect)
path.addClip()
image.draw(in: CGRect(origin: CGPoint.zero, size: size))
path.lineWidth = 2.0
UIColor.white.setStroke()
path.stroke()
}
DispatchQueue.main.async {
self.leftButton.image = finalImage.withRenderMode(.alwaysOriginal)
}
}.resume()
您还需要在数据任务上致电resume()
。