how to put the JSON data into UICollectionView in ios - ios

I try to get the Images from a JSON URL and place on UICollectionView
but i don't how to get images from JSON
#import "ViewController.h"
#import "CustomCell.h"
#interface ViewController ()
{
NSArray *arrayOfImages;
NSArray *arrayOfDescriptions;
NSMutableArray *json;
NSString *img;
NSMutableData *webData;
NSURLConnection *connection;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
/**/
[[self myCollectionView]setDataSource:self];
[[self myCollectionView]setDelegate:self];
NSString *urlString=[NSString stringWithFormat:#"http://ielmo.xtreemhost.com/array.php"];
NSURL * url=[NSURL URLWithString:urlString];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
NSLog(#"Connected");
webData=[[NSMutableData alloc]init];
}
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error is");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableArray *al=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(#"all array isn %#",al);
NSData* myData = [NSKeyedArchiver archivedDataWithRootObject:al];
NSLog(#"Data is data%#",myData);
NSError *error;
json=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
NSLog(#"Data is arrayjson%#",json);
for(int i=0;i<json.count;i++)
{
img=[NSString stringWithFormat:#"%#",[json objectAtIndex:i]];
NSLog(#"Data is arrayimage%#",img);
}
NSURL *urlOne=[NSURL URLWithString:img];
NSLog(#"Data is arrayurl%#",urlOne);
NSData *newData=[NSData dataWithContentsOfURL:urlOne];
UIImageView *imaegView=[[UIImageView alloc]initWithFrame:CGRectMake(38,0, 76, 96)];
[imaegView setImage:[UIImage imageWithData:newData]];
[self.myCollectionView addSubview:imaegView];
[[self myCollectionView]reloadData];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [arrayOfImages count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier=#"Cell";
CustomCell *cell=[ collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
[[cell myImage]setImage:[UIImage imageNamed:[arrayOfImages objectAtIndex:indexPath.item]]];
// [[cell myLabel]setText:[arrayOfDescriptions objectAtIndex:indexPath.item]];
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
i tried this code but in my output image are not display in my collectionView
please tell me how to retrieve images from json to My-collection VIew

As your JSON contains Image.
It must be encoded while transmitting mostly in Base64. Now you need to decode it to form NSData.
Once you have converted it to NSData then you can easily form an UIImage from it, after this you can show the image on collection view.

Related

titles appearing in collectionview when scroll up/down

when app run, titles(label in collectionview) are not appearing. scrolling up or down then titles are appearing. Also in numberOfItemsInSection,[news count] result is 0.
fffdgdfgdfghfghgfhgfhgghghhgjgjghjghjh
- (void)viewDidLoad
{
NSLog(#"viewDidLoad ");
[super viewDidLoad];
leftMenu.target=self.revealViewController;
leftMenu.action=#selector(revealToggle:);
self.title=#"Main";
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSURL *url=[NSURL URLWithString:#"http://www.test.com/ios/GetMainInfoByCat.php?cat_id=76"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
//self.collectionview.dataSource=self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data=[[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)Thedata
{
[data appendData:Thedata];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading ");
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
dnews=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
news=[dnews objectForKey:#"news_main_info_by_cat"];
NSString *str=[news valueForKey:#"img_url"];
//[self.collectionview reloadData];
//NSLog(#"%#",str);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *erroMsg=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Qoşula bilmədi. İnternet bağlantınızı yoxlayın" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[erroMsg show];
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
[collectionView.collectionViewLayout invalidateLayout];
return 1;
}
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
NSLog(#"%i",[news count]);
[collectionView.collectionViewLayout invalidateLayout];
return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell=(UICollectionView *)[collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
cell.newsTitle.text=[[news objectAtIndex:indexPath.row] objectForKey:#"post_title"];
//cell.newsImage.image=[NSData dataWithContentsOfURL:[NSURL URLWithString:[[news objectAtIndex:indexPath.row] objectForKey:#"img_url"]]];
//[[news objectAtIndex:indexPath.row] objectForKey:#"img_url"];
return cell;
}
Call reloadData
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading ");
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
dnews=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
news=[dnews objectForKey:#"news_main_info_by_cat"];
NSString *str=[news valueForKey:#"img_url"];
[self.collectionview reloadData];
}
Update: make sure IBoutlet is connected to collectionView
--> When you are scrolling collectionview or tableview at that time they are reloading the data so that when you are get your array after that please reload your scroll view this will sure help you.

Get data from JSON to table view

I have a JSON data from http://vmg.hdvietpro.com/ztv/home . I want to get text1,thumbnailImage value in this JSON after clicking getData button to get text1,thumbnailImage(NSString) values from JSON to table view. This is my code and after click button nothing happen. Thanks for help.
#interface ViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *moviesArray;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
moviesArray=[[NSMutableArray alloc]init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"Fail");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *response=[allDataDictionary objectForKey:#"response"];
NSDictionary *hotProgram=[response objectForKey:#"hot_program"];
NSArray *itemPageHot=[hotProgram objectForKey:#"page"];
for (NSDictionary*dic in itemPageHot) {
NSString *text1=[dic objectForKey:#"text1"];
[moviesArray addObject:text1];
}
[[self myTableView]reloadData];
}
- (IBAction)getData:(id)sender {
NSURL *url=[NSURL URLWithString:#"http://vmg.hdvietpro.com/ztv/home"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection){
webData =[[NSMutableData alloc]init];
NSLog(#"ket noi thanh cong");
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [moviesArray count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString*CellIndentifier=#"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIndentifier];
if(!cell){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
}
cell.textLabel.text=[moviesArray objectAtIndex:indexPath.row];
return cell;
}
You're not traversing the dictionary correctly. The key page is a child of key itemPage so this should work
NSArray *itemPageHot = [[hotProgram objectForKey:#"itemPage"] objectForKey:#"page"];
I'd recommend downloading a JSON inspector for issues like this. VisualJSON in the app store is what I use.

How to reloadData in tableView with didSelectedRowAtIndexPath and call group of methods in it

In my app I'm starting NSURLConnection, parsing XML, initialize array from this XML, and show it in the tableView. In ViewDidLoad I appeal to the server with a query parameter 0 , and it's returned for me string, after all conversion a have in tableView 4 rows - titles, and when i push on some of this titles, all process (connection to the server, parsing, arrays initialising, ) must be repeated. In didSelectedRowAtIndexPath I have to transmit section ID (so that the server sent me the correct data). How can I do it correctly? I'm establish connection in ViewDidLoad, how can I call it again?
My .m file:
#import "catalogViewController.h"
#import "XMLReader.h"
#interface catalogViewController ()
#end
#implementation catalogViewController
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { } return self;
}
//-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-CONNECTIONS METHOD START-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[_receivedData release];
NSString *errorString = [[NSString alloc] initWithFormat:#"Connection failed! Error - %# %# %#", [error localizedDescription], [error description], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; NSLog(#"%#",errorString);
[errorString release];
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-GET FULL DATA HERE-=-=-=-=-=-=-=-=--=-=-=-=-=-=-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *dataString = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
NSString *testXMLString = [NSString stringWithContentsOfURL:myURL usedEncoding:nil error:nil];
// -=-=-=-=-=-=-=-=-=-=Parse the XML into a dictionary-=-=-=-=-=-=-=-=-=-=
NSError *parseError = nil;
_xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART END-=-=-=-=-=-=-=
_titleArr = [[NSArray alloc] initWithArray:[[[_xmlDictionary objectForKey:#"result"] objectForKey:#"name"] valueForKey:#"text"]];
_IDArr = [[NSArray alloc] [[[_xmlDictionary objectForKey:#"result"] objectForKey:#"id"] valueForKey:#"text"]];
_priceArr= [[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"price"] valueForKey:#"text"]];
_ImageURLArr=[[NSArray alloc][[[_xmlDictionary objectForKey:#"result"] objectForKey:#"img"] valueForKey:#"text"]];
[connection release];
[_receivedData release];
[dataString release];
_didDataLoaded=TRUE;
[_myTableView reloadData]; // IBOutlet property
[self.tableView reloadData]; //default
}
//-=-=-=-=-=-=-=-=-=-=-Connection methods END-=-=-=-=-=-=-=-=-=-
- (void)viewDidLoad {
[super viewDidLoad];
_didDataLoaded=FALSE;
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-XMLPARSER PART START-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-==-=-=-=-=-=-=-=-=-=-=--=-=START Shit with connection-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=
NSString* params = #"request_params";
NSURL* url = [NSURL URLWithString:#"my URL"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connecting...");
_receivedData = [[NSMutableData data] retain];
} else {
NSLog(#"Connecting error");
}
}
//-=-==-=-=--=-==-=-=-=-=-=--=-==---=-=--==-=-=-=-=-TableView methods-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_didDataLoaded == FALSE) {
return 1;
}
else return self.titleArr.count;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; }
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"creatures"];
UIImage *creatureImage = nil;
if (_didDataLoaded == FALSE) {
cell.textLabel.text=#"Downloading...";
cell.detailTextLabel.text= #"downloading...";
} else {
cell.textLabel.text = [self.titleArr objectAtIndex:indexPath.row];
cell.detailTextLabel.text= _IDArr[indexPath.row];
NSString *img = self.ImageURLArr[indexPath.row];
creatureImage =[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:img]]]; cell.imageView.image = creatureImage;
}
return cell;
}
#end
You can move the relevant code from viewDidLoad to a specific method, something like:
- (void)loadXMLData {
// Initiate your loading/parsing
}
In viewDidLoad just call this method:
- (void)viewDidLoad {
[super viewDidLoad];
[self loadXMLData];
}
This way you can call [self loadXMLData] multiple times.
However... be careful with calling [tableView reloadData] from inside a UITableViewDelegate method implementation, as this will cause the tableview to call (at least some of the) delegate methods, which can cause recursive loops or other odd behaviour.

Parse links of a JSON file und download them

I want to create an App which parses the picture Links of a Facebook page and shows them in an iOS app (display them in tableView). But after I parsed the JSON file and added them to an array which should be downloaded nothing is displayed.
Here's the code:
- (void)viewDidLoad
{
self.edgesForExtendedLayout = UIRectEdgeNone;
[super viewDidLoad];
items = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/HuppFotografie/photos/uploaded/?fields=id,name,picture"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"fail with error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 250.0;
}
- (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 [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyImageCell";
ImageCell *cell = (ImageCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor clearColor];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"ImageCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (ImageCell *)currentObject;
break;
}
}
}
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:[items objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#"Placeholder.jpg"]];
cell.imageSource.text = [items objectAtIndex:indexPath.row];
return cell;
}
I really don't get why. I'm sorry if this question is stupid but I am coding just as a hobby and have not that great experience.
In fact your connection is asynchronous, so you just need to reload your table view programmatically to display loaded images:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
// Just add this line, in order to force reload when all your data is arrived
[self.tableView reloadData];
}

Error Drawing JSOn into UITableviewCell

I have json like this (have dictionary and array).
I want draw all json into UItableviewcell, but its not draw there
{ data: [
{
featured: true,
price: {
currency: "IDR",
amount: 5557679,
formatted: "Rp5.558.000"
},
] }
and this is my viewcontroller.h file
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
IBOutlet UITableView *mainTableView;
NSURL *URL;
NSDictionary *Deals;
NSArray *Deals_array;
NSMutableData *data;
}
#end
and this is my .m file
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title=#"SOme Apps";
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
URL = [NSURL URLWithString:[NSString stringWithFormat:#"http://someurl.com"]];
NSURLRequest *request=[NSURLRequest requestWithURL:URL];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
/*dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: URL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});*/
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
data=[[NSMutableData alloc] init];
NSLog(#"%#",data);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError* error;
Deals= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Deals_array = [Deals objectForKey:#"data"]; //2
NSDictionary* loan = [Deals_array objectAtIndex:0];
NSString *test=[loan objectForKey:#"featured"];
NSLog(#"%#",test);
[mainTableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"Error");
}
////set minimum section oftableview
-(int)numberOfTableviewSection : (UITableView *) tableView
{
return 1;
}
////set length uitableview
-(int) tableView :(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [Deals_array count];
}
///declaring uitableview
-(UITableViewCell *)tableView :(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell==nil){
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
cell.textLabel.text=[[Deals_array objectAtIndex:indexPath.row] objectForKey:#"featured"];
return cell;
}
#end
but its not draw the objectkey #test, can someone help me why?
Try doing the allocation
Deals_array = [[NSArray alloc] initWithArray:[Deals objectForKey:#"data"]];

Resources