Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an url image to button in ios with out doing NSData conversion

I wants to display a imageurl on button from the server.In the server i have image url's. I wants to do user interactions so i am use a button.

I have done below:

  1. Retrieve the image url from server.
  2. Convert > NSData to ImageObject
  3. Added the imageObject to setImageProperty then it's sucessfully displaying the image but the performance was slowly.

but I don't want to use NSData operations. Because it's take so much time.I wants to show the good performance in the app.

Is there any way to solve this problem?

like image 989
Jyoshna Avatar asked Mar 18 '23 14:03

Jyoshna


2 Answers

You can use SDWebImage library. its good library with caching functionality.

Just integrate below code.

add below code in appDidFinishLauching because using lifo execution last image will be download first

SDWebImageManager.sharedManager.imageDownloader.executionOrder = SDWebImageDownloaderLIFOExecutionOrder;

then import class in your viewcontroller.

#import "UIButton+WebCache.h"

and for integration

//set button image
[btn sd_setImageWithURL:[NSURL URLWithString:@"your string"] forState:UIControlStateNormal];

//set background image
[btn sd_setBackgroundImageWithURL:[NSURL URLWithString:@"your string"] forState:UIControlStateNormal];

you can also download image in background thread using below code

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"your string with encoding"];
    if (data)
    {
        UIImage *img = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (img)
               [btn setImage:btn forState:UIControlStateNormal];
        });
    }
});

But I presonally prefer SDWebImage library because it is good library and it will handle cache so you dont want to cache image.

like image 163
ChintaN -Maddy- Ramani Avatar answered Apr 06 '23 14:04

ChintaN -Maddy- Ramani


Another easy solution would be to use AFNetworking's UIButton category to set the image.

-(void)setImageForState:withURL:

This method will handle all the nitty gritty of downloading and converting the image. Your UI will not block because it is an async process. This will give your users a better overall experience.

like image 27
Andrew Monshizadeh Avatar answered Apr 06 '23 14:04

Andrew Monshizadeh