I have some project where i must paste image from JSON. I try to find any tutorial about this, try to see any video from this theme but nothing. So my problem have:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSDictionary *playlist =[allDataDictionary objectForKey:#"playlist_data"];
for (NSDictionary *diction in playlist) {
NSString *name = [diction objectForKey:#"text1"];
NSString *namesong = [diction objectForKey:#"text2"];
NSString *images = [diction objectForKey:#"image"];
NSLog(#"%#", images);
[array addObject:text1];
[array2 addObject:text2];
}
[[self tableTrack]reloadData];
}
I added text 1 to cell also text 2 its work perfect but how to add image to to array 3(image in cell in my tableView)?
I tried also to added for image but its not work for me:
NSURL *imageURL = [NSURL URLWithString:[appsdict objectForKey:#"image"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = imageLoad;
Please help with my problem or maybe give some tutorial with parse image from JSON, also youtube haven't perfect tutorial from JSON parse. Thanks!
Don't keep multiple data source like array1, array2, array3 etc. It is not good coding and will confuse while debugging/fixing issues. Instead maintain single array with information for displaying in individual cell of the table view.
for (NSDictionary *dict in playlist) {
// array is single data source
[array addObject:diction];
}
Then while assigning data to the table view cell use,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] autorelease];
}
cell.text1 = [[array objectAtIndex:indexPath.row] objectForKey:#"text1"];
cell.text2 = [[array objectAtIndex:indexPath.row] objectForKey:#"text2"];
//For displaying image by lazy loading technique use SDWebImage.
[cell.imageView setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] objectForKey:#"image"]] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
// If no place holder image, use this way
// [cell.imageView setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] objectForKey:#"image"]] placeholderImage:nil];
}
Like I mentioned in comments for lazy loading images from the URLs in JSON response, use SDWebImage. Usage is simple like I have shown above. Alternately you can implement lazy loading yourself by studying this sample code from Apple: LazyTableImages
Hope that helps!
According to https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html and http://www.json.org/ you can't keep binary data in JSON (unless it is in base64).
It seems there's a problem with your webdata which is not a valid JSON. Did you check what is set under #"image" key in that dictionary while debugging? You can use [NSJSONSerialization isValidJSONObject:webdata] as well to see if your data is ok.
//prepare your method here..
-(void)hitimageurl{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:replacephotostring]];
//set your image on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
if (_photosArray==nil) {
_showImageView.image = [UIImage imageNamed:#"noimg.png"];
} else {
[_showImageView setImage:[UIImage imageWithData:data]];
}
});
});
Related
I'm trying to create a feed just like the one in facebook. The problem is, the image on the succeeding rows will load the images from the initial rows and then correctly load their corresponding load. When you go to the top rows, the images previously loaded are gone. I've tried lazy loading but the problem persists. You could view the video to understand the problem better. (https://www.youtube.com/watch?v=NbgYM-1xYN4)
The images are asynchronously loaded and are fetched from our server.
Here are some Code:
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [latestPosts count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary * dataDict = [latestPosts objectAtIndex:indexPath.row];
CardCell *cell = [self.feedTable dequeueReusableCellWithIdentifier:#"CardCell"];
if (cell == nil) {
cell = [[CardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CardCell"];
}
[cell layoutSubviews];
NSURL *imageURL = [[NSURL alloc] initWithString:[dataDict objectForKey:#"post_holder_image"]];
NSURL *postImageURL = [[NSURL alloc] initWithString:[dataDict objectForKey:#"post_image"]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
NSData *postImageData = [NSData dataWithContentsOfURL:postImageURL];
dispatch_async(dispatch_get_main_queue(), ^{
cell.brandImage.image = [UIImage imageWithData:imageData];
cell.postImage.image = [UIImage imageWithData:postImageData];
});
});
cell.brandName.text = [dataDict objectForKey:#"post_holder"];
cell.postDateTime.text = [dataDict objectForKey:#"post_datetime"];
cell.postMessage.text = [dataDict objectForKey:#"post_content"];
return cell;
}
Use below method of UITableViewCell in your custom cell and set the image property to nil.
hope it will work for you.
-(void)prepareForReuse{
[super prepareForReuse];
// Then Reset here back to default values that you want.
}
There are a few problems with the above.
As mentioned above you need to use a image as a placeholder (i.e blank white or an image of your choice) in the cell init code AND cell reuse.
You really need to cache your images, only download an image once and then store it in a dictionary. i.e.:
UIImage *cachedImage = self.images[user[#"username"]];
if (cachedImage) {
//use cached image
[button setBackgroundImage:cachedImage forState:UIControlStateNormal];
}
else {
//download image and then add it to the dictionary }
where self.images is an NSMutableDictionary. You could also look into NSCache. If you don't cache the images you will find the table is very laggy when scrolling for a large number of rows because of the image conversion from data.
However this will not completely fix the problem if you start loading a table and scroll up and down very fast the images will appear to be in the wrong places and move around until they are all loaded. Cell reuse will confuse where to put the image. Make sure you put [tableView reloadItemsAtIndexPaths:#[indexPath]]; in your download block i.e.:
NSURL *imageURL = [[NSURL alloc] initWithString:[dataDict objectForKey:#"post_holder_image"]];
NSURL *postImageURL = [[NSURL alloc] initWithString:[dataDict objectForKey:#"post_image"]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
NSData *postImageData = [NSData dataWithContentsOfURL:postImageURL];
dispatch_async(dispatch_get_main_queue(), ^{
cell.brandImage.image = [UIImage imageWithData:imageData];
cell.postImage.image = [UIImage imageWithData:postImageData];
[tableView reloadItemsAtIndexPaths:#[indexPath]];
});
});
You need to set imageview.image nil or you should set your placeholder image while reusing cells. Here is same question Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling
Other than that if you are not using parse.com api ect. you can check https://github.com/rs/SDWebImage or https://github.com/AFNetworking/AFNetworking
There are tons of answer about this topic.
[cell layoutSubviews];
cell.brandImage.image = nil;
cell.postImage.image = nil;
So I have an application that reads records from a database and basically fills out a UITableView with the information from the DB. Some of the information includes an image, which it brings from an online server I have. Everything works fine, but the program is a little slow and scrolling is a little laggy/ jumpy, as its bringing all the images at once, instead of bringing them as I scroll. Is there a way to change it so that as I scroll it brings the next few visible records?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
static NSString *CellIdentifier = #"VersionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
STSneakerInfo *info = [_versionInfo objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.1];
[[cell textLabel] setNumberOfLines:2];
cell.textLabel.text = [[_uniqueBrand stringByAppendingString:#" "] stringByAppendingString: info.version];
cell.detailTextLabel.textColor = [UIColor grayColor];
cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:14.1];
cell.detailTextLabel.text = info.initialReleaseDate;
NSString *brandVersion = [[_uniqueBrand stringByAppendingString:#" "] stringByAppendingString:info.version];
NSString *underscoredBrandVersion = [brandVersion stringByReplacingOccurrencesOfString:#" " withString:#"_"];
NSString *underscoredBrandName = [_uniqueBrand stringByReplacingOccurrencesOfString:#" " withString:#"_"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: ([[[[[#"http://www.abc/img/" stringByAppendingString:underscoredBrandName] stringByAppendingString:#"/"] stringByAppendingString:underscoredBrandVersion] stringByAppendingString:#"/"] stringByAppendingString:#"default.jpg"])]];
cell.imageView.image = [UIImage imageWithData: imageData];
return cell;
}
you can use (https://github.com/rs/SDWebImage) to download image async. its easy and fast.
i prefered this library because it will handle your cache.
just write below code
[cell.imageView sd_setImageWithURL: [NSURL URLWithString: ([[[[[#"http://www.abc/img/" stringByAppendingString:underscoredBrandName] stringByAppendingString:#"/"] stringByAppendingString:underscoredBrandVersion] stringByAppendingString:#"/"] stringByAppendingString:#"default.jpg"])]];
you can also download image in background thread as per wenchenHuang answer above. using below code.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString: ([[[[[#"http://www.abc/img/" stringByAppendingString:underscoredBrandName] stringByAppendingString:#"/"] stringByAppendingString:underscoredBrandVersion] stringByAppendingString:#"/"] stringByAppendingString:#"default.jpg"])];
if (data)
{
UIImage *img = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
if (img)
cell.imageView.image = img;
});
}
});
Maybe this will help you.
The UITableView class never loads cells until they're about to appear onscreen.
I suggest you to use GCD to download image background.When finished,notice UI to change.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Download images
dispatch_async(dispatch_get_main_queue(), ^{
//Notice UI to change
});
});
Here's a full, real-world example with DLImageLoader
https://github.com/AndreyLunevich/DLImageLoader-iOS/tree/master/DLImageLoader
DLImageLoader is incredibly well-written, maintained constantly, is super-lightweight, and it can properly handle skimming.
It's difficult to beat and is used in many apps with vast numbers of users.
It is really an amazingly well maintained library - and on top of that the new Swift version is the pinnacle of excellence in Swift programming, it's a model for how to do it.
PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
#"http://graph.facebook.com/%#/picture?type=large",
[aFacebookUser objectForKey:#"id"] ];
__weak UIImageView *loadMe = self.cellImage;
[DLImageLoader loadImageFromURL:facebookImageURL
completed:^(NSError *error, NSData *imgData)
{
if ( loadMe == nil ) return;
if (error == nil)
{
UIImage *image = [UIImage imageWithData:imgData];
image = [image ourImageScaler];
loadMe.image = image;
}
else
{
// an error when loading the image from the net
}
}];
another real world example,
-(UICollectionViewCell *)collectionView:(UICollectionView *)cv
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger thisRow = indexPath.row;
BooksCell *cell;
cell = [cv dequeueReusableCellWithReuseIdentifier:
#"CellBooksNormal" forIndexPath:indexPath];
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
// set text items...
cell.title = #"blah;
// set image items using DLImageLoader...
__weak UIBookView *loadMe = cell.anImage;
[DLImageLoader loadImageFromURL:imUrl
completed:^(NSError *error, NSData *imgData)
{
[loadMe use:[UIImage imageWithData:imgData]];
}];
return cell;
}
Reason for your sluggish scroll is that you are downloading image on the main thread.
NSData *imageData = [[NSData alloc] initWithContentsOfURL:
That piece of code which is running on main thread, will make a network call and start downloading contents from server. And the execution halts there until its completed. Which means you wont be be able to scroll down anymore till image is loaded.
There are many workarounds for this. However the logic is same for all. Download image in a separate thread and load it once its completed.
If you are using AFNetworking in your project you can use setImageWithURL: on your UIImageView object. You need to include UIImageView+AFNetworking.h. It has a inbuilt caching mechanism and it will cache the images downloaded for that session.
I have a json array and I am using the following to retrieve data:
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//set up cities array
dronesArray = [[NSMutableArray alloc] init];
//Loop json array
for (int i = 0; i < jsonArray.count; i++)
{
//Create city/drone object
NSString * dID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * dName = [[jsonArray objectAtIndex:i] objectForKey:#"droneName"];
NSString * dPic = [[jsonArray objectAtIndex:i] objectForKey:#"dronePic"];
[dronesArray addObject:[[City alloc]initWithDroneName:dName andDronePic:dPic]];
}
}
The above displays the cells fine:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
City * droneObject;
droneObject = [dronesArray objectAtIndex:indexPath.row];
cell.textLabel.text = droneObject.droneName;
//Accessory
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
But it only displays the Name, there is no image. The images are stored in URL format e.g. http://www.domain.com/image.jpg in the sql database. How can I import the images to make it look like this format:
Ok So I added the following code to cellforrowatindexpath and it doesn't do anything:
[[cell imageView] setImage: [UIImage imageNamed:droneObject.dronePic]];
Whenever you need to download the image from the url and set it into the UIImageView. The best mechanism is to fetch the image from the url and store them in the cache and also set the downloaded image to the UITableView.
Now, when you will scroll the tableView than its content will be updated and you need to check wether for specific visible cell image is already downloaded, if downloaded than set it to the UIImageView else download it from the server.
In order to do this Very efficiently use SDWebImage Library. This is the most trusted and easy to use library.
Hope this will help you. Happy Coding :)
Assuming that you are trying to get image from url string
NSURL *url = [NSURL URLWithString:droneObject.dronePic];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[[cell imageView] setImage: [UIImage imageNamed:image]];
This is how I did it. The part that you pull the json data, you store the image by retrieving it from a URL string.
connectionDidFinishLoading
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
Movies *newMovie = [[Movies alloc] init];
newMovie.name = jsonElement[#"MovieID"];
NSString *urlString = [NSString stringWithFormat:#"*url of the image*%#", jsonElement[#"fileImage"]];
// www.example.com/img%#, /filename.jpg
NSURL *imageURL = [NSURL URLWithString:urlString];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
newMovie.imageName = image;
[_movies addObject:newMovie];
}
I created an NSObject named Movies to store the image and additional fields.
Movies.h
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) UIImage *imageName;
In my cellForRowAtIndexPath I create an imageview and set the image equal to the UIImage from Movies.h.
cellForRowAtIndexPath:
Movies *item = _feedItems[indexPath.row];
myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,50,50)];
myImageView.tag = indexPath.row;
myImageView.image = item.imageName;
[myCell addSubview:myImageView];
return myCell;
_feedItems is an NSArray
- (void)itemsDownloaded:(NSArray *)items
{
_feedItems = items;
[self.listTableView reloadData];
}
Short answer: Use AFNetworking and it's UIImageView category to set the cell's imageView's image in cellForRowAtIndexPath:
https://github.com/AFNetworking/AFNetworking/blob/master/UIKit%2BAFNetworking/UIImageView%2BAFNetworking.h
Long answer?
There are no images because you aren't setting the cell's imageView image property to anything in cellForRowAtIndexPath:. If you're working with just a URL you may want to consider loading and setting the images on your cell asynchronously so your table doesn't lock up as you scroll. This can be a tricky concept if you're new to it.
Anyway, there are lots of ways you can do this (and the AFNetworking solution does this for you out of the box):
Multithreading and Grand Central Dispatch for iOS Beginners Tutorial
Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling
Asynchronous downloading of images for UITableView with GCD
iOS: How to Download Images Asynchronously (And make your UITableView Scroll Fast)
AFNetworking
My problem is ---- I am using UITableView in custom cell when load data in tableview it is loading description and title also date but not load images in tableview.some times load all images in one row. When i am using this code scroll is working good but not load images in TableView. I want lazy load concepts. go to below link.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
newsobject=(newscustamCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (newsobject ==nil)
{
[[NSBundle mainBundle]loadNibNamed:#"newscustamCell" owner:self options:nil];
}
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[newsarry objectAtIndex:indexPath.row] objectForKey:#"image_file"]]];
/* Fetch the image from the server... */
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
/* This is the main thread again, where we set the tableView's image to
be what we just fetched. */
newsobject.allnewsimg.image = img;
// newsobject.allnewsimg.image=[UIImage imageWithData:data];
});
});
newsobject.allnewsdes.text=[[[newsarry objectAtIndex:indexPath.row] objectForKey:#"long_desc"]stringByStrippingTags];
newsobject.allnewslabel.text=[[newsarry objectAtIndex:indexPath.row] objectForKey:#"title"];
![enter image description here][1]
newsobject.timelabel.text=[[newsarry objectAtIndex:indexPath.row] objectForKey:#"date"];
return newsobject;
}
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[newsarry objectAtIndex:indexPath.row] objectForKey:#"image_file"]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
[tableView cellForRowAtIndexPath:indexPath].imageView.image = image;
});
});
You can use some Lib like SDWebImage or Afnetworking. Libs support lazy load image and auto cache this image.
All you need to do:
[cell.imageView setImageWithURL:[NSURL URLWithString:#"url of image"]
placeholderImage:nil];
I will share you some code. Please follow this code.
First you have to retrieve all data from server. After that load on tableview.
Try this code :
- (void)viewDidLoad
{
NSString *urlString=#"http://put your url";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
}
JSON delegate methods -------------
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *response_Array = [NSJSONSerialization JSONObjectWithData:self.responseRankData options:kNilOptions error:nil];
NSDictionary *dataDictionary=nil;
NSDictionary *imgurlDic=nil;
NSArray *imgDic=nil;
// I am retrieve image according to my url. So please edit this according to your url. i am just write the format.
for (int i=0; i < response_Array.count; i++)
{
imgurlDic = [imgDic objectAtIndex:i];
imgDic = [dataDictionary objectForKey:#"imageKey"]; // Take your Key according to URL
NSURL *url = [NSURL URLWithString:[imgurlDic objectForKey:#"url"]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
[self.Img_Array addObject:img]; // Adding all image in your image Array.
NSLog(#"imgurlDic == %#",imgurlDic);
}
[self.tableview reloadData]; // reload your tableview here.
}
Getting all image in your array you can use this array in your cellForRowAtIndexPath method or where you want to load the images.
Because of the way that table view cells are quickly queued/reused, by the time that your network request finishes loading the cell you are referring to might not be the same one you think it is (because it went offscreen and got queued and then reassigned to a different indexPath). Also, before returning the cell you need to make sure you reset its imageView’s image property to nil or some default value. See my answer here for more info: https://stackoverflow.com/a/23473911/91458
Also - it’s a good idea to keep a cache of the images you already retrieved. Check the NSCache class, which is very similar to using a mutable dictionary but with built in memory management, etc.
I also used that trick, but the threads and the indexes between threads make a mess so I searched and I found a great library on GitHub.
SDWebImage
You just need to #import <SDWebImage/UIImageView+WebCache.h> to your project, and you can define also the placeholder when image is being downloaded with just this code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier;
CustomCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
MyObject *object = (MyObject *)[self.list.array objectAtIndex:indexPath.row];
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
return cell;
}
It also cache downloaded images and gives you great performance.
Hope it will help you!
I hope this link help for you. by using asyn classes image loading async...
https://github.com/nicklockwood/AsyncImageView
Very new to AFNetworking, but after many SO questions... I've concluded that this is the solution to my issue.
I've got a hierarchy of JSON data loading my TableViewController cells dynamically. All of my text strings are loading appropriately but the image from my URL is not making it to my imageview.
Before utilizing the AFNetworking library, I had the images loaded, but I was experiencing some issues with the photos not staying loaded when I scrolled away and returned (they had to load again.)
What am I missing to get my images in there?
TableViewController.m
-(void)viewDidLoad {
[super viewDidLoad];
// Set the side bar button action. When it's tapped, it'll show up the sidebar.
siderbarButton.target = self.revealViewController;
siderbarButton.action = #selector(revealToggle:);
// Set the gesture
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
self.tableView.backgroundColor = [UIColor whiteColor];
self.parentViewController.view.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"logo_app_white.png"]];
NSURL *myURL = [[NSURL alloc]initWithString:#"http://domain.com/json2.php"];
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
NSError *error;
jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
[tableView reloadData]; // if tableView is unidentified make the tableView IBOutlet
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NeedCardTableViewCell *cell = (NeedCardTableViewCell *) [tableView dequeueReusableCellWithIdentifier:#"needCard"];
if (cell == nil)
{
cell = [[NeedCardTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"needCard"];
}
NSDictionary *needs = jsonArray[indexPath.row]; // get the data dict for the row
cell.textNeedTitle.text = [needs objectForKey: #"needTitle"];
cell.textNeedPoster.text = [needs objectForKey: #"needPoster"];
cell.textNeedDescrip.text = [needs objectForKey: #"needDescrip"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"userImage" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
_imageProfPic.image = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
return cell;
}
Have you tried using the AFNetworking+UIImageView category? You can then call:
[_imageProfPic setImage:[NSURL URLWithString:#"http://myimageurl.com/imagename.jpg"]];
This will make a request and then set the returned image to your UIImageView's UIImage without you having to do anything else. You should also consider initializing NSURLCache in your AppDelegate:
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
diskCapacity:10 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:cache];
Take a look at NSHipster's run down on NSURLCache. This will help reload images, and all your requests, much faster the second time around. This is increasingly important when dealing with images and tables.
Manage to figure this one out with the use of this tutorial:
Networking Made Easy with AFNetworking
I used the final snippet of code to get my desired result:
NSURL *url = [[NSURL alloc] initWithString:[movie objectForKey:#"artworkUrl100"]];
[cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:#"placeholder"]];
I cut the second line of his code because I already have an if statement in my PHP/JSON
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NeedCardTableViewCell *cell = (NeedCardTableViewCell *) [tableView dequeueReusableCellWithIdentifier:#"needCard"];
if (cell == nil)
{
cell = [[NeedCardTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"needCard"];
}
NSDictionary *needs = jsonArray[indexPath.row]; // get the data dict for the row
cell.textNeedTitle.text = [needs objectForKey: #"needTitle"];
cell.textNeedPoster.text = [needs objectForKey: #"needPoster"];
cell.textNeedDescrip.text = [needs objectForKey: #"needDescrip"];
NSURL *url = [[NSURL alloc] initWithString:[needs objectForKey:#"userImage"]];
[cell.imageProfPic setImageWithURL:url];
return cell;
}
It worked like a charm, and the tutorial was pretty helpful since I'm a rookie with AFNetworking.