I want to fetch an image from server URL in to my bar button item. I am using code like below but it is gives an error : Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value . how can I solve this problem ? Note: loadImg func is an extension and its working another controller. and serverURL is my class for profile data.
let imageView = UIImageView()
imageView.loadImg(url: URL(string: self.serverURL.ppUrl!)!) // this line give error
let customView = UIButton(type: .system)
customView.setImage(imageView.image, for: .normal)
customView.backgroundColor = .white
let barButtonItem = UIBarButtonItem(customView: customView)
navigationItem.leftBarButtonItem = barButtonItem
extension UIImageView {
public func loadImg(url: URL) {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
}