2

I am attempting to set an URL image to an UIButton in swift 4. I am using AFNetworking to load my images from the urls. I am seeing what is the best route to take in order to set the image to the button.

Using .setImage() or setImageWith() does not work with urls and uibuttons.

This is the URL being used:

let imageUrl = URL(string: baseUrl + profile)

JSharpp
  • 459
  • 1
  • 9
  • 21
  • Download the button from the URL, save it locally if required, apply it to the button – MadProgrammer Oct 19 '18 at 21:12
  • https://github.com/AFNetworking/AFNetworking/blob/master/UIKit%2BAFNetworking/UIButton%2BAFNetworking.h There should be all the methods you want there without the needs of using a different library. – Larme Oct 22 '18 at 17:03
  • Please see my answer here : https://stackoverflow.com/a/56616298/3904109 – DragonFire Jun 17 '19 at 00:33

2 Answers2

6

You can use SDWebImage it has a category/extension for the UIButton too

btn.sd_setImage(with:URL(string: "Your_url"), forState:.normal)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • I am trying this cell.bProfileImage.sd_setImage(with:URL(string: individualChatsListArray[indexPath.row].profile_image), forState:.normal) but getting error Value of optional type 'UIButton?' must be unwrapped to refer to member 'sd_setImage' of wrapped base type 'UIButton' – DragonFire Jun 16 '19 at 04:43
  • replace `cell.bProfileImage.` with `cell.bProfileImage!.` – Shehata Gamal Jun 16 '19 at 09:38
  • But, If I am using kingfisher library? – iDeveloper Aug 01 '19 at 08:31
0

I'm posting because the current answer suggests another library (SDWebImage) while AFNetworking already provides an extension for UIButton with UIButton + AFNetworking.h (and .m).

The declaration are in Objective-C, but you should be able to use the Swift equivalent one in your code:

- (void)setImageForState:(UIControlState)state
                 withURL:(NSURL *)url;
- (void)setImageForState:(UIControlState)state
                 withURL:(NSURL *)url
        placeholderImage:(nullable UIImage *)placeholderImage;
- (void)setImageForState:(UIControlState)state
          withURLRequest:(NSURLRequest *)urlRequest
        placeholderImage:(nullable UIImage *)placeholderImage
                 success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
                 failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;

There is also the same versions for the backgroundImage.

Larme
  • 24,190
  • 6
  • 51
  • 81