I have a UIImageView in side a UIView, which displays an object #"photos" in a JSON Array as such: http://topmobiletrends.com/wp-content/uploads/2013/10/screen568x568-14.jpeg
My NSLog tells me that all the objects have been parsed correctly. But the UIImageViews inside UIViews show the same image, I believe it is the first object [0]. I need to have the views show each image for all of the objects for the #"photos" key.
Here is my code for my ViewController.m:
. . .
#interface ViewController ()
{
NSInteger index;
}
//#property (nonatomic, weak)NSURL *imageURL;
#end
#implementation ViewController
#synthesize menuButton;
#synthesize myImage;
#synthesize priceLabel;
-(void)viewDidLoad{
[super viewDidLoad];
NSURL *bburl = [NSURL URLWithString:#"http://www.suchandsuch.com/api/sites"];
NSData *jsonData = [NSData dataWithContentsOfURL:bburl];
NSURLSession *session = [NSURLSession sharedSession];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:bburl];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:bburl completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error){
NSLog(#"%#", response);
NSData *data = [[NSData alloc]initWithContentsOfURL:location];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSString *imageURLString = [[[dataDictionary objectForKey:#"sites"] objectAtIndex:index] objectForKey:#"photo"];
NSURL *imageURL = [NSURL URLWithString:[imageURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"sites : %#", imageURLString);
NSArray *sitesArray = [dataDictionary objectForKey:#"sites"];
NSMutableArray *photos = [[NSMutableArray alloc]initWithArray:sitesArray];
for (NSDictionary *item in sitesArray) {
MyObject *current = [MyObject alloc];
current.name = [item objectForKey:#"name"];
current.url = [item objectForKey:#"url"];
current.price = [item objectForKey:#"price"];
current.photo = [item objectForKey:#"photo"];
[photos addObject:current];
NSLog(#"%#", current.photo);
}
for (MyObject *photo in photos)
{
dispatch_async(dispatch_get_main_queue(),^{
UIView *dView = [[UIView alloc]initWithFrame:CGRectMake(30,30,258,229)];
UIImage *image = [UIImage imageWithData:data];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
imageView.frame = CGRectMake(30, 30, 258, 229);
//Get image from url
[self.imageView setImageWithURL:imageURL];
//[self.myImage addSubview:imageView];
[dView addSubview:imageView];
[self.view addSubview:dView];
// priceLabel.text = [[[dataDictionary objectForKey:#"sites"] objectAtIndex:index] objectForKey:#"price"];
});
}
}];
[task resume];
}
There are a few issues with the code.
You are adding both NSURL and name string to the photos array but when reading you are expecting all of them to be photos.
I would recommend create a data structure called Photo which contains
#interface PhotoClass :NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSURL *url;
#property (nonatomic, strong) NSString *price
#property (nonatomic, strong) NSString *photo;
#end
That way you can do the following when parsing your data.
PhotoClass *current = [PhotoClass alloc];
current.name = [item objectForKey:#"name"];
current.url = [item objectForKey:#"url"];
current.price = [item objectForKey:#"price"];
current.photo = [item objectForKey:#"photo"];
// Add to array
[photos addObject:current];
And then when you are ready to display use the url from each PhotoClass object.
The next issue in your code is with the image view setup. First of all You will need to create as many ImageViews. each one needs to be offset to the other can be visible behind that image. Plus the image view seems to be getting set in many diff ways. Is that just a typo? :
for (PhotoClass *photo in photos)
{
dispatch_async(dispatch_get_main_queue(),^{
UIView *dView = [[UIView alloc]initWithFrame:CGRectMake(50,50,258,229)];
// The frame of each of the frames needs to be offset a little ..
// so you need to figure out how to calculate that for each image.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:photo.url]];
[dView addSubview:imageView];
[self.view addSubview:dView];
....
}];
}
At the end of the loop you should have as many image views in view as objects in photos.
Disclaimer - code not compiled and typed directly into stackoverflow browser
Related
I have a base url and I have the image names in a array extracted from there server .I am using a collection view, I have to display all the 23 images in the collection view I have two problems
when I try to access cell.imageview.image it says no property image view in cell but in custom cell.h file I have created the outlet and I am using storyboard
2.as one is string base url and other end path or filename of the images in array extracted from john from server
this is how I get from data--
{
"added_by" = 1;
"category_id" = 182;
"category_image" = "shots.png";
"category_name" = Shots;
sequance = 19;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 168;
"category_image" = "classiccocktail.png";
"category_name" = "Classic Cocktails";
sequance = 20;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 167;
"category_image" = "sprit.png";
"category_name" = "Non Alcoholic Bevereges";
sequance = 21;
status = 0;
"store_id" = 1;
},
{
"added_by" = 1;
"category_id" = 162;
"category_image" = "nonalcoholic.png";
"category_name" = "Non Alcoholic Coolers";
sequance = 22;
status = 0;
"store_id" = 1;
}
this is nslog of server reply
This is the slog of the array in which I have stored the data
2017-06-13 10:16:39.181 MenuBar[1703:94836] (
"kinfisherultra.png",
"impotedbeernew.png",
"blendedwhiskyne.png",
"johywalkerbluee.png",
"singlemaltnew.png",
"americanwishkynew.png",
"irishwishkynew.png",
"Belvedere-Vodka.png",
"Ginnew.png",
"Tequilanew.png",
"rumnew.png",
"amarula.png",
"aprities.png",
"breezernew1.png",
"conganbrndynew.png",
"wine&sparkling.png",
"bottels.png",
"cocktailpitchers.png",
"mocktails.png",
"shots.png",
"classiccocktail.png",
"sprit.png",
"nonalcoholic.png"
)
and I have a base url how to get all these images in collection view?
this is customcell.h file
#import <UIKit/UIKit.h>
#interface CustomCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) IBOutlet UILabel *lbl;
#end
customcell.h file
#import "CustomCell.h"
#implementation CustomCell
-(void)awakeFromNib {
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onButtonTapped:)];
[tap setNumberOfTapsRequired:1];
[self addGestureRecognizer:tap];
[super awakeFromNib];
}
-(void)onButtonTapped:(id)sender
{
//the response to the gesture.
//mind that this is done in the cell. If you don't want things to happen from this cell.
//then you can still activate this the way you did in your question.
}
#end
view controller.hfile
if(!sharedSessionMainQueue){
sharedSessionMainQueue = [NSURLSession sessionWithConfiguration:nil delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
}
[[sharedSessionMainQueue dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSDictionary *temp=jsonDict;
NSLog(#"Req cust:%#",requestReply);
NSLog(#"requestReply cust liqour category: %#", jsonDict);
NSArray *imgNameArray = [temp valueForKey: #"category_name"];
NSLog(#"$$$%#$$$",imgNameArray);
self.iname=[jsonDict valueForKey:#"category_image"];
NSLog(#"%#",self.iname);
//[self imagedl];
NSDictionary *tempz=[jsonDict valueForKey:#"category_name"];
Photos = [NSArray arrayWithObjects:#"http://test.kre8tives.com/barebones/upload/%#",self.iname, nil];
NSLog(#"^^^%#",tempz);
//NSLog(#"$$%#",[Photos objectAtIndex:]); //Here can show Img's values correctl
// }
// self.recipeImageView.image = [UIImage imageNamed:self.recipeImageName];
}] resume];
_barbutton.target = self.revealViewController;
_barbutton.action = #selector(revealToggle:);
//[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background"]];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)geti{
NSString *temps= [NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/%#",self.iname];
UIImage *temp;
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:temps]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"%#",response);
//temp.image= [UIImage imageWithData:data];
}];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 23;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//[CustomCell registerClass:[CustomCell class] forCellWithReuseIdentifier:reuseIdentifier];
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
[[[cell contentView] subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
UIView * contents=[[UIView alloc] initWithFrame:cell.contentView.bounds];
[contents setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:contents];
_imageView.image;
// set tag to the indexPath.row so we can access it later
[cell setTag:indexPath.row];
// add interactivity
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onButtonTapped:)];
[tap setNumberOfTapsRequired:1];
[cell addGestureRecognizer:tap];
NSString *fileName = [NSString stringWithFormat:#"%#",self.iname]; //objectAtIndex:indexPath];
NSLog(#"%#",fileName);
NSString *baseurl=[NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/"];
NSDictionary *doors = [NSMutableArray new];
NSString *base=[NSString stringWithFormat:#"http://test.kre8tives.com/barebon/upload/"];
NSLog(#"%#",doors);
NSString *path = [NSString stringWithFormat:#"%#/%#", baseurl, _iname];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgage = [[UIImage alloc] initWithData:data];
//NSString *filePath = [baseurl stringByAppendingPathComponent:fileName];
NSDictionary *dict = self.iname[indexPath.row];
NSLog(#"%#", [self.iname objectAtIndex: indexPath.row]);
NSString *filePath=[NSString stringWithFormat:#"%#%#",baseurl,fileName];
NSString *paths = [NSString stringWithFormat:#"%#/%#", baseurl, [[dict valueForKey:#"category_image"] objectAtIndex: indexPath.row]];
NSLog(#"%#",dict);
NSString *temps= [NSString stringWithFormat:#"%#",filePath];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:paths]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"%#",response);
UIImage *imgage = [[UIImage alloc] initWithData:data];
_imageView.image=[[UIImage alloc] initWithData:imgage];
_imageView.image=[[NSData alloc]initWithData:data];
//imageView.contentMode = UIViewContentModeScaleAspectFill;
// _imageView.clipsToBounds = YES;
//imageView.tag = IMAGE_VIEW_TAG;
}];
if (cell.selected) {
cell.backgroundColor = [UIColor blueColor]; // highlight selection
}
else
{
cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}
Register your custom cell in viewDidLoad method
[yourCollectionView registerNib:[UINib nibWithNibName:#"CustomCell" bundle:nil] forCellWithReuseIdentifier:#"your Cell Identifier"];
And then you will write on cellForItemAtIndexPath method
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"your Cell Identifier";
CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSDictionary *dict = imageAry[indexPath.row];
//SdWebimage to load image
[cell.imgUser sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", baseUrl, dict[#"imageName"]]];
return cell;
}
Download SDWebimageImageLoader to use of async image downloader with cache support.
NSString *path = [NSString stringWithFormat:#"%#/%#", baseUrl, imageName];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imgage = [[UIImage alloc] initWithData:data];
pass this image to your imageview.
As you are loading images from server, you can also use SDWebImage for image caching purpose.
https://github.com/rs/SDWebImage
I'm trying to pass dogData from my ViewController to PetViewController (through a modal segue). That said, for some reason when I attempt to pass the dogData (NSMutableArray), I get this error:
[__NSArrayI length]: unrecognized selector sent to instance
Any idea why this might be? See code below (hope this is enough info, tried to trim it).
ViewController.h
#property (strong, nonatomic) NSMutableArray *dogData;
ViewController.m
NSMutableDictionary *viewParamsDogs = [NSMutableDictionary new];
[viewParamsDogs setValue:#"mydogs" forKey:#"view_name"];
[DIOSView viewGet:viewParamsDogs success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.dogData = [responseObject mutableCopy];
NSLog(#"This is the dog photo data %#", self.dogData);
[operation responseString];
NSDictionary *dic = [responseObject valueForKey: #"field_pet_photo_path"];
NSArray *arr = [dic valueForKey: #"und"];
NSDictionary *dic2= [arr objectAtIndex : 0];
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSMutableCharacterSet *characterSetToTrim = [NSMutableCharacterSet characterSetWithCharactersInString:#"()\""];
[characterSetToTrim formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
path = [path stringByTrimmingCharactersInSet:characterSetToTrim];
if([path length]>0) {
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = image;
} else {
NSString *ImageURL = #"http://url.ca/paw.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.dogimageView.image = [UIImage imageWithData:imageData];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
- (IBAction)openPetProfile:(id)sender {
PetViewController *petProfile = [[PetViewController alloc] init];
petProfile.petSubDetail = self.dogData;
[self presentViewController:petProfile animated:YES completion:nil];
}
PetViewController.h
#property (nonatomic, copy) NSMutableArray *petSubDetail;
#property (weak, nonatomic) IBOutlet UILabel *petName;
PetViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.petName.text = [self.petSubDetail valueForKey:#"petname"];
}
Data output:
"field_petname" = {
und = (
{
format = "<null>";
"safe_value" = Pebbles;
value = Pebbles;
}
);
};
Your code should be like,
NSdictionary *dict = [self.petSubDetail objectForKey:#"field_petname"];
NSArray *arr = [dict objectForKey:#"und"];
NSdictionary *dict1 = [arr objectAtIndex : 0];
self.petName.text = [dict1 valueForKey:#"value"];
where you need " in key use \"
hope this will help :)
Good afternoon,
I'm trying to display the data in my UITableViewController (CarTableViewController) and at the moment the rows are being populate with the correct info and also the refreshControl is working fine (and very fast, like 1 second) but the first time I entry in my App the data is not displayed (I have to move the screen with my finger and then the data is displayed). (I have to wait like +15 seconds until it appears automatically, but sometimes is not showing).
What can I do in order to display the data automatically and fast?
I tried to move the reloadData into every method and it's always the same and I don't know what else to do...! I will be much appreciated if you can help me with that.
CarTableViewController.m
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
#synthesize likes = _likes;
#synthesize comments = _comments;
#synthesize username = _username;
#synthesize refuser = _refuser;
#synthesize profileImage = _profileImage;
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
[self.tableView reloadData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
self.refreshControl.backgroundColor = [UIColor blackColor];
self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(fetchJson)
forControlEvents:UIControlEventValueChanged];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (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
{
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"]];
[cell.carImage setImageWithURL:imageURL
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
options:SDWebImageRefreshCached];
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"image"]];
[cell.profileImage setImageWithURL:imageURL2
placeholderImage:[UIImage imageNamed:#"image"]
options:SDWebImageRefreshCached];
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ShowCarDetails"])
{
CarDetailViewController *detailViewController = [segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
detailViewController.carDetailModel = [[NSArray alloc]
initWithObjects:
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"date"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"id"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"imagen"],
nil];
}
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://mywebsite.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];
[self.refreshControl endRefreshing];
}
}
);
}
#end
CarTableViewController.h
#import <UIKit/UIKit.h>
#interface CarTableViewController : UITableViewController
#property (nonatomic, strong) IBOutlet UITableView *tableView;
#property (nonatomic, strong) NSMutableArray *carImages;
#property (nonatomic, strong) NSMutableArray *carMakes;
#property (nonatomic, strong) NSMutableArray *carModels;
#property (nonatomic, strong) NSMutableArray *likes;
#property (nonatomic, strong) NSMutableArray *comments;
#property (nonatomic, strong) NSMutableArray *username;
#property (nonatomic, strong) NSMutableArray *refuser;
#property (nonatomic, strong) NSMutableArray *profileImage;
#property (nonatomic, strong) NSMutableArray *jsonArray;
#end
Thanks in advance.
Your problem is in fetchJson. You're calling reloadData on a background thread, which has unpredictable results. You need to make sure that you call any UI methods on the main thread.
Replace your code with the following:
- (void)fetchJson
{
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];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://mywebsite.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
error:&error];
for (NSDictionary * jsonObject in _jsonArray)
{
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];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
});
);
}
i have code to display a single image from json array data in a UIImageView.
i want to display all images in multiple UIImageViews.
plz suggest me how to loop images to display all.
json array data link:
Here's code from my app
NSString *urlString=[NSString stringWithFormat:#"http://ielmo.xtreemhost.com/array.php"];
NSURL * url=[NSURL URLWithString:urlString];
NSData *data =[NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableArray *json=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",[json objectAtIndex:0]);
NSString *imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:0]];
NSURL * urlone=[NSURL URLWithString:imageString];
NSData *datanew =[NSData dataWithContentsOfURL:urlone];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
[imageView setImage:[UIImage imageWithData:datanew]];
testView = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 300.0f, 300.0f, 200.0f)];
[testView addSubview:imageView];
[self.view addSubview:testView];
NSMutableArray *arr=[[NSMutableArray alloc] init];
NSString *urlString=[NSString stringWithFormat:#"http://ielmo.xtreemhost.com/array.php"];
NSURL * url=[NSURL URLWithString:urlString];
NSData *data =[NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableArray *json=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%d",[json count]);
NSLog(#"%#",[json objectAtIndex:0]);
NSString *imageString;
for (int i=0; i<[json count]; i++) {
imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:i]];
[arr addObject:imageString];
}
NSLog(#"%#",arr);
// NSString *imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:0]];
NSURL * urlone=[NSURL URLWithString:imageString];
NSData *datanew =[NSData dataWithContentsOfURL:urlone];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
[imageView setImage:[UIImage imageWithData:datanew]];
UIView * testView = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 300.0f, 300.0f, 200.0f)];
[testView addSubview:imageView];
[self.view addSubview:testView];
After parsing JSON response use follow code
UIScrollView *testView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,320,480)];
for(int i=0; i<[json count]; i++){
NSLog(#"%#",[json objectAtIndex:i]);
NSString *imageString=[NSString stringWithFormat:#"%#",[json objectAtIndex:i]];
NSURL * urlone=[NSURL URLWithString:imageString];
NSData *datanew =[NSData dataWithContentsOfURL:urlone];*
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,i*480,320,480)];
[imageView setImage:[UIImage imageWithData:datanew]];
[testView addSubview:imageView];
}
[self.view addSubView:testView];
*Note: Now you are going with Synchronous Request to download & load images in the view. It is not a good approach. Use Asynchronous requests for downloading images and loading them.
Find the following URL for asynchronous image downloading
Asynchronous downloading of images for UITableView with GCD
you can get an image dictionary into array like this, into data object
Suppose i have PostClubDC class with posDC obj
for(NSDictionary *returnDicto in dataArray)
{
PostClubDC *postDC = [[PostClubDC alloc] init];
NSDictionary * returnDict = [returnDicto objectForKey:#"club_info"] ;
postDC.postID = [[returnDict objectForKey:#"Id"]integerValue];
postDC.postName = [returnDict objectForKey:#"name"];
postDC.postImage = [returnDict objectForKey:#"image"];
[yourDataArray addObject:postDC];
}
I'm building an RSS reader app, following tutorials and what not.
So far I've built a custom class named blogPost, which stores the post name and post author, with a designated initializer based on the name.
I'm attempting to pull the thumbnail image of the post in my for loop, and display it in the cell where I'm currently showing the title and author attributes.
I successfully pulled the image URL and parsed it from JSON but can't seem to store the image in a UIImage.
//Custom header for BlogPost
#interface BlogPost : NSObject
#property (nonatomic, strong) NSString *title;
#property (nonatomic, strong) NSString *author;
#property (nonatomic, strong) UIImage *image;
// Designated Initializer
- (id) initWithTitle:(NSString *)title;
+ (id) blogPostWithTitle:(NSString *)tile;
#end
And here's the tableViewController
[super viewDidLoad];
NSURL *blogUrl = [NSURL URLWithString:#"http://www.wheninmanila.com/api/get_recent_summary/"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogUrl];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.blogPosts = [NSMutableArray array];
NSArray *blogPostsArray = [dataDictionary objectForKey:#"posts"];
for (NSDictionary *bpDictionary in blogPostsArray) {
BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:#"title"]];
blogPost.author = [bpDictionary objectForKey:#"author"];
NSURL *thumbURL = [bpDictionary objectForKey:#"thumbnail"];
NSData *thumbData = [NSData dataWithContentsOfURL:thumbURL];
blogPost.image = [[UIImage alloc] initWithData:thumbData];
[self.blogPosts addObject:blogPost];
}
Change this line:
NSURL *thumbURL = [bpDictionary objectForKey:#"thumbnail"];
To this:
NSURL *thumbURL = [NSURL urlWithString:[bpDictionary objectForKey:#"thumbnail"]];
The values in your dictionary will be NSStrings, which are not the same thing as NSURL's.
You are using NSURL instead of a NSString and NSString does not respond to selector isFileURL (thats why you get the exception). I assume your thumbnail is a string so you should get it as NSString and than convert it to NSURL as follows :
NSString *thumbAsString = [bpDictionary objectForKey:#"thumbnail"];
NSURL *thumbURL = [NSURL URLWithString:thumbAsString];