thanks for taking the time to read my question.
i have an app project using swift that has a function using sdwebimage. This function is pretty simple and works perfectly in my code.
However, this function is called many times throughout my app and can be slightly messy in code.
I would like to create a swift extension file that can be accessed every time a UIimageView.image needs to be downloaded from my database.
my current download code is:
usersImage1 = the uiimageview to be set.
user.imageOne = the image URL string from firebase
usersImage1.sd_setImage(with: URL(string: user.imageOne!)) { (image, error, cache, urls) in
if (error != nil) {
self.usersImage1.image = UIImage(named: "1")
} else {
self.usersImage1.image = image
}
}
i am looking for something like the following:
An extension that can be called where uiimageview and imageurl can be replaced when the function is called with the required URL string and uiimageview.
extension UIImageView {
func loadImageFromDatabase(image: UIImageView, imageUrl: string) { image.sd_setImage(with: URL(string: imageUrl!)) { (image, error, cache, urls) in if (error != nil) { self.image.image = UIImage(named: "1") } else { self.image.image = image } } }
}
Then in viewcontroller use the function like this:
self.userimage1.loadImageFromDatabase(imageUrl)
thanks in advance for your help.
If I have understood your desire correctly, you can achieve this with a manager class instead of extension, which will be responsible for downloading image for you. Create a class like below:
class ImageDownloaderManager {
class func loadImageFromDatabase(userImage: UIImageView, imageUrl: String, completionHandler: @escaping (Bool)-> Void) {
image.sd_setImage(with: URL(string: imageUrl!)) { (image, error, cache, urls) in
if (error != nil) {
userImage.image = UIImage(named: "1") // set your placeholder image maybe.
completionHandler(false)
} else {
userImageimage = image
completionHandler(true)
}
}
completionHandler(true)
}
}
It has a completion block where you can understand if your image was downloaded successfully or not from where-ever you call this function. Lets say you call this method from a viewController's viewDidLoad method as following:
override func viewDidLoad() {
super.viewDidLoad()
ImageDownloaderManager.loadImageFromDatabase(image: yourImage, imageUrl: yourImageURL) { (isSucceeded) in
if isSucceeded {
// It was successful, you could download the image successfully, do smth
} else {
// It was not successful image couldnt be downloaded, placeholder image has been set.
}
}
}