I need to display the background image of a button by giving the image source from an external URL instead of downloading the image. Is there a possible way to do this in swift.
Asked
Active
Viewed 1,065 times
-3
-
You mean you want to download and attach the image at runtime rather than during development? – Joakim Danielson Feb 07 '19 at 08:59
-
Yes.. I need to display image on the button at runtime using a image url. – Tharindu Pradeep Feb 07 '19 at 09:01
-
1pod 'SDWebImage', pod 'Kingfisher' – SPatel Feb 07 '19 at 10:02
2 Answers
2
You can use SDWebImage POD.
yourBtn.sd_setImage(with: <#T##URL?#>, for: <#T##UIControl.State#>, completed: <#T##SDExternalCompletionBlock?##SDExternalCompletionBlock?##(UIImage?, Error?, SDImageCacheType, URL?) -> Void#>)

Taimoor Suleman
- 1,588
- 14
- 29
-1
First you need to get the image data from external URL and then use the image
if let url = URL(string: "YOUR-IMAGE-URL-HERE") {
do{
let data = try Data(contentsOf: url)
self.imageVar = UIImage(data: data)
if let myImage: UIImage = self.imageVar {
YOUR-BUTTON-NAME.setImage(myImage, for: .normal)
}
}catch {
print("error")
}
}

Saurabh
- 745
- 1
- 9
- 33
-
Saurabh is there a way without downloading the image data because I have about 50 images to download in one view controller and it takes time to download all of them and show in the view. – Tharindu Pradeep Feb 07 '19 at 09:20
-
1Fetching data synchronously, especially on main thread, is always a bad idea. – mag_zbc Feb 07 '19 at 09:20
-
-
1@TharinduPradeep You have to download the images if you want to display them. – Saurabh Feb 07 '19 at 09:34
-