Image not showing using Nsurlconnection Post method - ios

I am using nsurlconnection in POST method and created four array for "see","buy","updated","image".Displayed in tableviewcell but "image" not showing. image in "url in png format".
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error;
json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error];
NSLog(#"%#",json);
sellArray = [json valueForKeyPath:#"BranchByList.sell"];
buyArray = [json valueForKeyPath:#"BranchByList.buy"];
updataedArray = [json valueForKeyPath:#"BranchByList.updated"];
imageArray = [json valueForKeyPath:#"BranchByList.flag_image"];
[_datad reloadData];
}
tableview delegate methods are:
-(NSInteger)numberOfSectionsInTableView:(UITableView *) tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section{
return [sellArray count];
return [buyArray count];
return [updataedArray count];
return [imageArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"path" forIndexPath:indexPath];
cell.sellbl.text=[sellArray objectAtIndex:indexPath.row];
cell.buylbl.text=[buyArray objectAtIndex:indexPath.row];
cell.updatedlbl.text = [updataedArray objectAtIndex:indexPath.row];
cell.imglbl.image = [UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];
return cell;
}
-(void)tableView: (UITableView *) tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
}

You are directly assigning url to image! That will not work at all.
You need to first add the url to NSUrl and then convert the url in to data by using NSData and then assign the data to the image.
To accomplish it add below line of code in your code:
NSURL *url = [NSURL URLWithString:[imageArray objectAtIndex:indexPath.row]];
NSData *data = [NSData dataWithContentsOfURL:url];
cell.imglbl.image = [UIImage imageWithData:data];
I'm posting one more example for more understanding. I have a url and i need to display the image from that url to my device. For that m using the below line of code:
NSURL *url = [NSURL URLWithString:#"http://1.bp.blogspot.com/-9yd6LPL2N6U/VatsUdMffPI/AAAAAAAAAl4/Pq1S6Q20fy0/s1600/hello_world.gif"];
NSData *data = [NSData dataWithContentsOfURL:url];
_imgView.image=[UIImage imageWithData:data];
Above url is just a random url of a image taken from google.
Result:

You are calling image like,
cell.imglbl.image = [UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];
It is fine if image is available in your project otherwise you need to download it from url which you getting in response like,
NSData *data = [NSData dataWithContentsOfURL:#"you url"];
UIImage *img = [UIImage imageWithData:data];
cell.imglbl.image = img;
or you can use SDWebImage, greate third party library to caching the image.
hope this will help :)

Add SDWebImage
in your project and use this code
[cell.imglbl setImageWithURL:[NSURL URLWithString:[imageArray objectAtIndex:indexPath.row]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
instead of
cell.imglbl.image = [UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];
return cell;

It seems like you set not an image to cell.imglbl.image, but the url of it..
cell.imglbl.image = [UIImage imageNamed:[imageArray objectAtIndex:indexPath.row]];
You can use some third party library like SDWebImage to asynchronous download image.
https://github.com/rs/SDWebImage
(Or download it synchronous like this
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *image = [UIImage imageWithData:data];
)
Also I would recommend you to have a Dictionary to keep already downloaded images, where the keys will be the indexPaths of cells.
Hope it help :)

Related

unable to use objectAtIndex property

im trying to load a set of images from web and display it on the screen within a collection view. Following is my code
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.layer.cornerRadius = 5;
NSURL *url = [NSURL URLWithString:
#"http://elatewiki.org/images/thumb/Google.png/120px-Google.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
//recipeImageView.image = [UIImage imageNamed:[recipePhotos objectAtIndex:indexPath.row] ];
recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[0] ]];
return cell;
}
but i have to use the objectAtIndex:indexPath.row property along with imageWithData so the image can be swiped . Is there any ways through which i can use objectAtIndex:indexPath.row along with NSData dataWithContentsOfURL ?
You can use this:
NSString *url_str = [NSString stringWithFormat: #"%#",[recipPhotoUrl objectAtIndex: indexPath.item]];
NSURL *url = [NSURL urlWithString:url_str];
recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
What's the for?
NSURL *url = [NSURL URLWithString:
#"http://elatewiki.org/images/thumb/Google.png/120px-Google.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
Anyway, you were close to solution....
if (recipPhotoUrl.count > indexPath.row)
{
recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[indexPath.row]]];
}
But still, you are doing this operations on the main thread and you, for sure, block the UI, the scroll will not be smooth.
It also not so sure as you're accessing the index without checking if the array has a sufficient dimension.
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
should be placed in a common function.For example -(void)viewDidLoad, add a property reference to image .
recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[0]]];
change to
recipeImageView.image = self.image;

How to get image from json response and display in collection view ios

I am new to iOS and I am getting an image url from json.. Now I want to display it on collection view. I am doing the below code. But not able to display image in collection view .Anybody Can help me out for this?enter code here
// Collection View Code
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return imageArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
if(!cell)
{
cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50,0, 50, 80)];
myImageView.tag = 101;
[cell.contentView addSubview:myImageView];
}
NSString *myImage = [imageArray objectAtIndex:indexPath.row];
NSString *ImageString = [myImage stringByReplacingOccurrencesOfString:#"" withString:#"%20"];
NSLog(#"Image String %#",ImageString);
NSURL *imageURL = [NSURL URLWithString:ImageString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImageView *img = (UIImageView*)[cell.contentView viewWithTag:101];
img.backgroundColor = [UIColor redColor ];
cell.backgroundView = [UIImage imageWithData:imageData];
return cell;
}
// Json Service
NSDictionary *get = #{#"uid":[uidSave valueForKey:#"uid"],#"pro":proNumber};
NSLog(#"Dictionary Data which is to be get %#",get);
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"r=%#",jsonInputString];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",displayCaseUrl]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil)
{
jsonDict = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"Values =======%#",jsonDict);
NSMutableDictionary *imageDict = [jsonDict valueForKey:#"images"];
NSLog(#"Image Dictionary :- %#",imageDict);
imageArray = [imageDict valueForKey:#"image_url"];
NSLog(#"MY Array Image :- %#",imageArray);
// Json Respone from where image is to be get
Image Dictionary :- (
{
"image_url" = "http://zapponomics.net/claimservice/parcelimage/1486154806image0.jpg";
"img_for" = "Front view of parcel";
"pro_number" = orange;
}
)
2015-08-26 10:09:05.806 ClaimCloud[1997:87342] MY Array String :- (
"http://zapponomics.net/claimservice/parcelimage/1486154806image0.jpg"
)
//////// USIng Like this but does not work
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50,0, 50, 80)];
myImageView.tag = 101;
[cell.contentView addSubview:myImageView];
NSString *myImage = [imageArray objectAtIndex:indexPath.row];
[self loadImageFromURL:[NSURL URLWithString:[myImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] callback:^(UIImage *image) {
myImageView.image = image;
}];
return cell;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, 0, 0,200);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(100,80);
}
- (void) loadImageFromURL: (NSURL*) url callback:(void (^)(UIImage *image))callback {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSData * imageData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:imageData];
callback(image);
});
});
}
There is a very good library named SDWebImage which will help you to load the image from a URL.As in the above answer of #poojathorat you are converting the image to data, if the images are of larger size, than you will get the memory problem, but this library will manage the memory also.So in my opinion use this library.
Just drag the SDWebImage folder in your project and import
#import "UIImageView+WebCache.h"
then to load the image from URL use this method
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
it will also manage the cache of images.
And if you don't want to include the library then use this function
- (void) loadImageFromURL: (NSURL*) url callback:(void (^)(UIImage *image))callback {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSData * imageData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:imageData];
callback(image);
});
});
}
And use this function like this
[self loadImageFromURL:[NSURL URLWithString:["yourURL" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] callback:^(UIImage *image) {
yourImageView.image = image;
}]
No need of replacing space by %20.Directly apply by follwing way.
NSString *myImage = [imageArray objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:myImage];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
cell. myImageView.image = [UIImage imageNamed:img];

UITableView with JSON data very slow and freezing

Good morning,
Yesterday I finally made my first TableViewController with JSON parsing data from my database but now I have a problem with that:
The app is taking almost 9-10 second to load and show 3 entries.
When I navigate with scroll down the TableView it freezes when it displays a new image.
I'm going to show you my code because I don't know why is this happening, maybe it's because the images are really big (they are made with the iPhone camera and stored in my FTP).
Do you know why my App is so slow when loading the results and then navigation through them?
ViewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
}
TableView:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.likes.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"likes"];
cell.comments.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"comments"];
cell.username.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
cell.refuser.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user_ref"];
cell.modelLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"]];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * carPhoto = [UIImage imageWithData:imageData];
cell.carImage.image = carPhoto;
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"image"]];
NSData * imageData2 = [NSData dataWithContentsOfURL:imageURL2];
UIImage * carPhoto2 = [UIImage imageWithData:imageData2];
cell.profileImage.image = carPhoto2;
return cell;
}
FetchJSON:
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
#try
{
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
}
#finally
{
[self.tableView reloadData];
}
}
);
}
And that's my JSON output file:
[{"id":"15","user":"1","imagen":"http:\/\/website.com\/juliaroberts.jpg","date":"2014-09-13","userID":"1","image":"http:\/\/m.c.lnkd.licdn.com\/mpr\/mpr\/shrink_200_200\/p\/3\/000\/25b\/1fe\/200e9f3.jpg","username":"*jordi","id_post":"15","likes":"5","comments":"2","post_id":"15","user_ref":"*juliaroberts"},{"id":"16","user":"1","imagen":"http:\/\/website.com\/onedirection.png","date":"2014-11-11","userID":"1","image":"http:\/\/m.c.lnkd.licdn.com\/mpr\/mpr\/shrink_200_200\/p\/3\/000\/25b\/1fe\/200e9f3.jpg","username":"*jordi","id_post":"16","likes":"1","comments":"0","post_id":"16","user_ref":"*onedirection"},{"id":"17","user":"1","imagen":"http:\/\/website.com\/onedirection.png","date":"2014-11-09","userID":"1","image":"http:\/\/m.c.lnkd.licdn.com\/mpr\/mpr\/shrink_200_200\/p\/3\/000\/25b\/1fe\/200e9f3.jpg","username":"*jordi","id_post":"17","likes":"3","comments":"3","post_id":"17","user_ref":"*onedirection"}]
Thanks in advance.
The problem is that your images are being downloaded synchronously and thay block main thread. So every time you see tableview cell, image will be downloaded.
This is the most expensive code:
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * carPhoto = [UIImage imageWithData:imageData];
You should always avoid heavy operations to be run on the same thread as UI runs (main thread).
The workaround for you is:
1). Move any images downloading code to the background threads.
2). Return downloaded UIImage to the main thread to show in the UI.
3). Cache the image once it downloaded to save traffic.
Basically you can use a lot of 3rd party libraries for these tasks. The most popular is SDWebImage:
https://github.com/rs/SDWebImage
You should try to measure the performance bottlenecks of your app using Instruments. Reading this post on raywenderlich.com is a simple introduction to profiling this sort of issues.
Based solely on the code you posted, it looks like you're fetching the images for the cars in the main thread which causes the performance hickups. The line of code that does this is:
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
and the reason is the fact that dataWithContentsOfURLis run synchronously in the current thread which in this case is the main thread. The Apple Documentation of dataWithContentsOfURL acknowledges this and recommends using dataTaskWithURL:completionHandler: instead.

Xcode table view lag when scrolling

(void)bilgileriYukle
{
NSMutableArray *yemekIsimleri = [[NSMutableArray alloc] init];
NSMutableArray *resimIsimleri = [[NSMutableArray alloc] init];
NSURL *myURL = [[NSURL alloc]initWithString:#"http://www.sevgilezzeti.com/WebServices/tarifler.php"];
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
if (myData == nil)
{
NSLog(#"INTERNET YOK YADA VERI CEKEMEDI");
}
else
{
NSLog(#"INTERNET VAR VERI CEKILDI");
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:nil];
for (id element in jsonArray)
{
NSString *durum = [element objectForKey:#"durum"];
if([durum isEqualToString:#"1"])
{
[yemekIsimleri addObject:[element objectForKey:#"yemekadi"]];
NSString *gelenYemekAdi =[element objectForKey:#"kapakresmi"];
NSString *imagePathKapak = #"http://sevgilezzeti.com/Admin/yemekresimkapak/";
combined = [NSString stringWithFormat:#"%#%#", imagePathKapak, gelenYemekAdi];
[resimIsimleri addObject:combined];
}
}
}
_TarifAdi=yemekIsimleri;
_ResimAdi=resimIsimleri;
}
///////////////////////////////////////////////////////////////////////////////////////
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"TableViewCell" forIndexPath:indexPath];
NSUInteger row = [indexPath row];
cell.TitleLabel.text = _TarifAdi[row];
NSCache *_imageCache;
UIImage *image = [_imageCache objectForKey:#"DenemeRes"];
if (image == nil) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_ResimAdi[row]]];
image = [UIImage imageWithData:data];
[_imageCache setObject:image forKey:#"DenemeRes"];
}
cell.ThumbImage.image = image;
return cell;
}
I can get images from URL and can see images but when I scroll the table view, it's very slow and lagging. How can I fix this problem ?
It's pretty easy and straightforward to load images synchronously in table view cells, however it's evil, because it would cause the lag when you scroll it, because it's actually trying to load and display the images as you're scrolling.
Therefore, you must avoid loading images synchronously, but asynchronously instead, using a different thread other than the main thread, so that the scrolling and loading + displaying images can be done dependently, avoiding any kind of lag.
This is possibly a duplicate question, since it's already been asked and there are tutorials out there, but since I myself always had a problem with this on my first iOS app and found it very confusing, I'm posting the answer here, hoping it's helpful.
Try adding something like this to your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath:
// Get the filename to load.
NSString *imageFilename = [imageArray objectAtIndex:[indexPath row]];
NSString *imagePath = [imageFolder stringByAppendingPathComponent:imageFilename];
[[cell textLabel] setText:imageFilename];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
dispatch_sync(dispatch_get_main_queue(), ^{
[[cell imageView] setImage:image];
[cell setNeedsLayout];
});
});
dataWithContentsOfURL is blocking your main thread, that'w why the table is acting like it is. You should load images in back thread so that the main thread can handle UI without interruptions
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url cachePolicy:0 timeoutInterval:kTimeoutInterval];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
// set to ImageView
cell.ThumbImage.image = image;
}];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"TableViewCell" forIndexPath:indexPath];
cell.tag = indexPath.row;
cell.imageView.image = nil;
// Rounded Rect for cell image
CALayer *cellImageLayer = cell.imageView.layer;
[cellImageLayer setCornerRadius:35];
[cellImageLayer setMasksToBounds:YES];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^(void) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_ResimAdi[indexPath.row]]];
UIImage *image = [[UIImage alloc] initWithData:data];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
if (cell.tag == indexPath.row) {
CGSize itemSize = CGSizeMake(70, 70);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[cell setNeedsLayout];
}
});
}
});
cell.TitleLabel.text = _TarifAdi[indexPath.row];
return cell;
}

Downloading image from a url into a UIImageVIew dynamically

I am trying to insert and image into a UIImageView from a url. I used the following code to do so.
When running the program gets stuck at
NSURL *url = [NSURL URLWithString:urlstring];
In the below code and it shows "Thread 1 : signal SIGABRT" on that particular line.
Can someone help me with this and tell if the format that i used is correct or what i had did wrong??
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newoffer";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *temp = [product objectAtIndex:indexPath.row];
UILabel *Label = (UILabel *)[cell viewWithTag:201];
Label.text = [temp objectForKey:#"item_name"];
UIImageView *Image = (UIImageView *)[cell viewWithTag:200];
NSString *urlstring=[temp objectForKey:#"image_url"];
NSURL *url = [NSURL URLWithString:urlstring];
NSData *data = [NSData dataWithContentsOfURL:url];
Image.image = [UIImage imageWithData:data];
return cell;
}
Change this code:
NSURL *url = [NSURL URLWithString:urlstring];
NSData *data = [NSData dataWithContentsOfURL:url];
Image.image = [UIImage imageWithData:data];
To:
dispatch_queue_t myqueue = dispatch_queue_create("myqueue", NULL);
// execute a task on that queue asynchronously
dispatch_async(myqueue, ^{
NSURL *url = [NSURL URLWithString:[urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];;
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
Image.image = [UIImage imageWithData:data]; //UI updates should be done on the main thread
});
});
As mentioned by others, an Image Caching library like SDWebImage will help a lot because even with this implementation, you just push the download process to a background thread so the UI does not get stucked, but you are not caching anything.
Try this
[image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.vbarter.com/images/content/1/9/19517.jpg"]]]];
For async downloading
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.vbarter.com/images/content/1/9/19517.jpg"]]]];
});
if url is dynamic then
NSString *stringUrl; // this can be any valid url as string
[image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:stringUrl]]]];
NSData *data = [NSData dataWithContentsOfURL:url];
will load imageData synchronous, that means main thread will be blocked .
Use the project on github:SDWebImage for image asynchronous loading and cache.
There's probably better libraries that do this now, but I have always been using this for my projects and it works well: AsyncImageView. There are other alternatives like SDWebImage
But basically, you don't want to use
NSData *data = [NSData dataWithContentsOfURL:url];
because it will block the main thread until the image is downloaded. To avoid this you might want to use something asynchronous, like the above two libraries.
For example, with AsyncImageView, it becomes as easy as:
myImageView.imageURL = someNSURL;

Resources