Pass Json Value to UICollection View - ios

i want to display my images in grid view. i have used UICollection view controller,data which is i'm passing in JSON format.i cant able to display images using JSON format. Can anyone pls find my mistake? Here is my code
#interface ReceipeCollectionViewController()
{
NSMutableData *webdata;
NSURLConnection *connection;
NSMutableArray *contentarray;
NSMutableArray *array;
}
#end
#implementation ReceipeCollectionViewController
(void)viewDidLoad
{
[super viewDidLoad];
[array removeAllObjects];
[[self collectionView]setDelegate:self];
[[self collectionView]setDataSource:self];
array = [[NSMutableArray alloc] init];
}
(void)viewDidAppear:(BOOL)animated
{
NSString *serverurl=#"http://wesotech.com/web/myrecipe/web_services/recipe_listing.php?";
NSURL *url=[NSURL URLWithString:serverurl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webdata=[[NSMutableData alloc]init];
}
else
{
NSLog(#"Connection failure");
}
}
(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
{
NSError *error;
NSArray *results=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:&error];
[array removeAllObjects];
[array addObjectsFromArray:results];
[[self collectionView]reloadData];
}
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webdata setLength:0];
}
(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [array count];
}
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.mySpinner stopAnimating];
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell.contentView viewWithTag:100];
recipeImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:#"image"]]]];
UITextField *recipeTitleView =(UITextField *)[cell.contentView viewWithTag:101];
recipeTitleView.text=[[array objectAtIndex:indexPath.row]valueForKey:#"recname"];
return cell;
}
#end
My JSON Format is,
[
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704658059030.jpg","recname":"Italian Chicken","recid":"1"},
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704653421637.jpg","recname":"Fast Food Friday","recid":"2"},
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704648912893.jpg","recname":"Honey Clazed Lamb Chops","recid":"3"}
]

Instead of escaping your URL with \, use percentage encoding in your JSON and decode it back to unescaped string using the below code
NSString *imageUrl = #"http%3A%2F%2Fwesotech.com%2Fweb%2Fmyrecipe%2Frecipeimages%2F2016080614704658059030.jpg";
NSString *url = [imageUrl stringByRemovingPercentEncoding];
Another important point: Since you are loading an image with http://, you should set Allow Arbitrary Loads to YES under App Transport Security Settings in your info.plist file.
Also, make a note that it is not advisable to set allow arbitrary loads as it would result in security issues. It would be better if you
could have all your network calls to use https://

Make a class of tableViewCell and assign that class name to cell of collectionView in utility area. Make the outlet of imageView in tableViewCell Class and access it in cellForItemAtIndexPath delegate method.
Then assign the image with this code :
[cell. recipeImageView sd_setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:#"image"]]];
This will surely help you.

Related

AFNetworking EXC_BAD_ACCESS (code=2, address=0x0) in downloadTask

I have an App that compiles a list of customer specific reports for a customer after login. These reports are showing up and I have put a "view" button which is supposed to download the PDF file, and bring it up to view within the app.
At this stage, it looks as though I have a memory issue when the view button is pressed, and I am not sure how to find where the issue is. HEre is my code:
#import "reportsTestViewController.h"
#import "ReportsDataObject.h"
#import "Session.h"
#import "AFNetworking.h"
#interface reportsTestViewController ()
#end
#implementation reportsTestViewController
#synthesize response;
#synthesize myDataIvar;
#synthesize viewReportPressed;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
reportsTable.delegate = self;
reportsTable.dataSource = self;
self.sections = [[NSMutableDictionary alloc] init];
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
#pragma mark NSURLConnection Delegate Methods
//
//Create your request pointing to the test page
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.tesg.com.au/allCustBuild.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//initialize it when you create your connection
if (connection){
self.myDataIvar = [[NSMutableData alloc] init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[self.myDataIvar setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.myDataIvar appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"Connection Failed: %#", error.userInfo);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//this is where you would parse the data received back from the server
NSString *responseString = [[NSString alloc] initWithData:self.myDataIvar encoding:NSUTF8StringEncoding];
NSLog(#"Received Data: %#",responseString);
[self setupReportsFromJSONArray:self.myDataIvar];
}
-(void)connectionWasASuccess:(NSData *)data{
[self setupReportsFromJSONArray:data];
}
-(void)setupReportsFromJSONArray:(NSData*)dataFromReportsArray{
BOOL found;
NSError *error;
// NSMutableArray *reportsArray = [[NSMutableArray alloc] init];
NSArray *arrayFromServer = [NSJSONSerialization JSONObjectWithData:dataFromReportsArray options:0 error:&error];
if(error){
NSLog(#"error parsing the json data from server with error description - %#", [error localizedDescription]);
}
else {
reportsArray = [[NSMutableArray alloc] init];
for(NSDictionary *eachReport in arrayFromServer)
{
ReportsDataObject *report = [[ReportsDataObject alloc] initWithJSONData:eachReport];
[reportsArray addObject:report];
NSString *c = [[eachReport objectForKey:#"title"] substringToIndex:3];
found = NO;
for (NSString *str in [self.sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
if (!found)
{
[self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
}
}
}
NSLog(#"Array Populated");
NSLog(#"%u reports found",reportsArray.count);
//Now you have your reportsArray filled up with all your data objects
for (NSDictionary *eachReport in arrayFromServer)
{
[[self.sections objectForKey:[[eachReport objectForKey:#"title"] substringToIndex:3]] addObject:eachReport];
}
// Sort each section array
for (NSString *key in [self.sections allKeys])
{
[[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"title" ascending:YES]]];
}
[reportsTable reloadData];
}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewReportPressed:(UIButton*)button {
NSLog(#"Button successfully Pressed");
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://tesg.com.au/portal/media/reports/1367365180_367 Collins Passive April 2013.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *theResponse) {
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
return [documentsDirectoryPath URLByAppendingPathComponent:[theResponse suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
}];
[downloadTask resume];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSUInteger count = [[self.sections allKeys] count];
NSLog(#"Number of sections: %d", count);
return count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//We check against table to make sure we are displaying the right number of cells
// for the appropriate table. This is so that things will work even if one day you
//decide that you want to have two tables instead of one.
{
NSUInteger count = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
NSLog(#"Number of rows in section: %d", count);
return count;
}
}
//- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//return [[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
// }
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
//The beauty of this is that you have all your data in one object and grab WHATEVER you like
//This way in the future you can add another field without doing much.
NSUInteger count = [[self.sections allKeys] count];
if(count == 0){
cell.textLabel.text = #"no reports to show";
}
else{
NSDictionary *Reports = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [Reports objectForKey:#"title"];
cell.detailTextLabel.text = [Reports objectForKey:#"building"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(viewReportPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"View" forState:UIControlStateNormal];
button.frame = CGRectMake(180.0f, 5.0f, 150.0f, 30.0f);
[cell addSubview:button];
// in the future you can grab whatever data you need like this
//[currentReport buildingName], or [currentReport reportName];
}
return(cell);
}
#end
When the view button is pressed in any of the cells, I get the NSLog saying 'button successfully pressed' but it crashes immediately after with error
[downloadTask resume]; Thread 1:EXC_BAD_ACCESS (code=2, address=0x0)
Any ideas how to fix this?
If you get a EXC_BAD_ACCESS with an address of 0x0, that generally means that a nil value was used in a context where nil is not permitted.
In this case, it is a result of the fact that your URL string is not valid. Spaces are not allowed. Thus your resulting URL variable is nil, which will result in the behavior you describe. You probably want to percent escape the URL string, e.g.:
NSString *URLString = #"http://tesg.com.au/portal/media/reports/1367365180_367 Collins Passive April 2013.pdf";
NSURL *URL = [NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
To identify this sort of exception in the future, you can use exception breakpoints, which will often help identify the offending line of code. Or just carefully review your code code for situations where you may have unintentionally passed a nil value to a method that does not accept it.
If, however, you ever get a EXC_BAD_ACCESS with a value other than 0x0, that is often a result of an attempt to use a previously deallocated object. (Not always, but frequently. Fortunately, ARC has made this sort of problem less common.) Clearly, this is not the case here, but you asked how one would identify a situation where you attempt to use a previously deallocated object.
To diagnose that situation, you would generally turn on "zombies" (see Running Your Application with Diagnostics). By the way, once you finish your diagnostics with zombies, make sure you turn them back off, as you don't want to keep zombies turned on (especially in a production app).
Anyway, in this case, because the address was 0x0, it wasn't a result of a deallocated object, but rather the problem was the incorrect usage of a nil value, caused by the invalid URL.

Updating UILabel text in custom cell

In my UITableViewController there are custom cells populated from JSON. Each cell has a UILabel showing a text value (#"valoracion"). When the user selects a row, a detail view from the cell object is shown. At this detail view, the user can change the value of valoracion. If the user goes back to the UITableViewController, valoracion should show the new value, but actually it shows the old value.
What should I do to update valoracion in the UITableViewController, when the user goes back from the detail view to the UITableViewController.
UPDATED***
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell =[tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell ==nil){
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
//cell.backgroundColor = [UIColor clearColor];
cell.nombreEmpresaLabel.text = [[categorias objectAtIndex:indexPath.row] objectForKey:#"nombreEmpresa"];
//[[cell contentView] setBackgroundColor:[UIColor clearColor]];
//cell.textLabel.backgroundColor = nil;
// cell.detailTextLabel.backgroundColor=nil;
cell.textLabel.textColor = [UIColor whiteColor];
cell.direccionEmpresaLabel.text= [[categorias objectAtIndex:indexPath.row] objectForKey:#"direccionEmpresa"];
NSMutableString *logo = [[NSMutableString alloc]initWithString:#"http://mujercanariasigloxxi.appgestion.eu/logos/"];
NSString *imageURL = [[categorias objectAtIndex:indexPath.row] objectForKey:#"strImagen"];
cell.meGustaHits.text = [[categorias objectAtIndex:indexPath.row] objectForKey:#"valoracionEmpresa"];
if(imageURL != nil && ![imageURL isEqual:[NSNull null]])
{
[logo appendString:imageURL];
NSURL *logoURL = [NSURL URLWithString:logo];
NSData *logoData = [NSData dataWithContentsOfURL:logoURL];
cell.logoImage.image = [UIImage imageWithData:logoData];
}
else{
cell.logoImage.image = [UIImage imageNamed:#"icono80"];
}
return cell;
}
Inside viewDidLoad method:
//URL definition where php file is hosted
int categoriaID = [[categoriaDescription objectForKey:#"idCategoria"] intValue];
NSString *string = [NSString stringWithFormat:#"%d", categoriaID];
NSLog(#"CATEGORIA ID STGRING %#",string);
NSMutableString *ms = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/empresaslist.php?id="];
[ms appendString:string];
// URL request
NSLog(#"URL = %#",ms);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
//URL connection to the internet
[[NSURLConnection alloc]initWithRequest:request delegate:self];
And now the JSON delegate methods and didSelecRowAtIndexpath method:
//methods to perform the connection and population of data
-(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
{
//if data received network indicator not visible
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
//array waterfalls populated via JSON from database
categorias = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
NSLog(#"THE DA TA &#",categorias);
[self.tableView reloadData];
}
//only in case of error
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The download could not complete - please make sure you are connected to eithre 3G or WiFi" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
//if no connection network indicator not visible
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetalleEmpresaViewController *detailViewController =[self.storyboard instantiateViewControllerWithIdentifier:#"detailEmpresaViewController"];
detailViewController.title =[[categorias objectAtIndex:indexPath.row]objectForKey:#"idCategoria"];
detailViewController.detalleDescription = [categorias objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
Try call [tableview reloadData] method and make sure that you have correct implementation of tableview delegate methods.
If place where you change and save your JSON is another, than tableViewController, then put reloadData method in viewDidAppear of tableViewController class. If you saving JSON in other method of same tableViewController, then place reloadData in last line of this method.

How to show json data in table view in xcode

i am new to ios and am currently working in json. I am just using itunes top 10 albums which to be displayed in table view i received data i formatted and displayed in table view but i can able to display only album name but i want to display all details of particular album which is to be displayed in same cell.
Here is my full code
- (void)viewDidLoad
{
[super viewDidLoad];
albumtop=[[NSMutableArray alloc]init];
[[self itunestTable]setDataSource:self];
[[self itunestTable]setDelegate:self];
NSURL *url=[NSURL URLWithString:#"https://itunes.apple.com/in/rss/topalbums/limit=10/json"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
albumdata =[[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[albumdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[albumdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"error in connection");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *alldata =[NSJSONSerialization JSONObjectWithData:albumdata options:0 error:nil];
NSDictionary *album =[alldata objectForKey:#"feed"];
NSArray *total =[album objectForKey:#"entry"];
for(NSDictionary *top in total)
{
NSDictionary *albumname =[top objectForKey:#"im:artist" ];
title =[albumname objectForKey:#"label"];
[albumtop addObject:title];
}
[[self itunestTable]reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [albumtop count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if(!cell)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier];
}
cell.textLabel.text=[albumtop objectAtIndex:indexPath.row];
return cell;
}
Program working well
My output will be like this
---------------------------------
Jones
---------------------------------------
carry Kim
---------------------------------------
i can able to fetch single value only how can i display all the details of the album like this
----------------------------------
Jones
no.tracks 10
price 180
---------------------------------------
carry Kim
no.tracks 10
price 180
---------------------------------------
how i can achieve this help me.. thanks in advance
You need to add Thee label in your UITableViewCell.
And fetch each Value as you needed. It is simple fetch as you fetch value of name and put it to relevant UILabel.
You also need to expand size of your cell of UITableView by following method.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
return 80;// write as you need.
}
you have to use costum UITableviewCells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"BDCustomCell"];
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"BDCustomCell" owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = [topLevelObjects objectAtIndex:0];
}
return cell;
}

Can not set UICollectionView number of items in section from a json response

I'm very new to iOS programming and am trying to set UICollectionView items from a json response.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self downloadJSONData];
/* uncomment this block to use subclassed cells */
[self.collectionView registerClass:[CVCell class] forCellWithReuseIdentifier:#"cvCell"];
/* end of subclass-based cells block */
// Configure layout
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(150, 150)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.collectionView setCollectionViewLayout:flowLayout];
[self.collectionView reloadData];
}
-(void) downloadJSONData {
NSURL *serviceUrl = [[NSURL alloc]initWithString:#"http://myurlhere.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:serviceUrl];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)responsedata {
[self.data appendData:responsedata];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error : %#", error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data",[self.data length]);
NSString *txt = [[NSString alloc] initWithData:self.data encoding: NSASCIIStringEncoding];
NSLog(#"response data %#", txt);
self.dictionaryData = [txt JSONValue];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//NSMutableArray *sectionArray = [self.dataArray objectAtIndex:section];
self.jsonArray = [self.dictionaryData objectForKey:#"images"];
return [self.jsonArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
// Setup cell identifier
static NSString *cellIdentifier = #"cvCell";
/* Uncomment this block to use nib-based cells */
// UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
// UILabel *titleLabel = (UILabel *)[cell viewWithTag:100];
// [titleLabel setText:cellData];
/* end of nib-based cell block */
/* Uncomment this block to use subclass-based cells */
CVCell *cell = (CVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];
NSString *cellData = [data objectAtIndex:indexPath.row];
[cell.titleLabel setText:cellData];
/* end of subclass-based cells block */
// Return the cell
return cell;
}
When I run the code, it displays nothing. What I want is it displays items and the quantity is equal to the array's count. And one more thing, any suggestion on how to load images asynchronously into the collectionview?
I'm sorry for my english. and I'd be glad if anyone can help me on this.
Thanks. cheers!
In the connectionDidFinishLoading method add:
[self.collectionView reloadData];
For Asyn image loading, you can check any of the following,
SDWebImage
AsyncImageView
LazyTableImages - It is for UITableView, but you can use the same concept for UICollectionView

iOS Basic Request to webservice

Can anyone point me in the right direction of a good tutorial or possibly answer this question.
I have some JSON to be returned on my web server
{
first_name: "Joe";
last_name: "Smith";
department: "Human Resources";
}
How do I make a http request to get this information at the click of a button and display as text on the iphone.?
Complete newbie so please 'dumb' down.
create a jsonviewcontroller class
#import <UIKit/UIKit.h>
#interface JSONViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>
{
NSString *label;
}
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
- (IBAction)getTop10AlbumAction:(id)sender;
#end
then in implementation class:-
#import "JSONViewController.h"
#interface JSONViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSString *category;
}
#end
#implementation JSONViewController
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray 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(#"Failed with Error");
}
this is the place where actual parsing happens, we fetch the title of albums from respective dictionary and arrays. to understand this first go to this link http://jsonviewer.stack.hu/#http://itunes.apple.com/us/rss/topalbums/limit=10/json this is the json viewer which shows the structure of the content that we are going to access. dont panic! its really easy if u try parsing some json urls
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"];
NSArray *arrayOfEntry=[feed objectForKey:#"entry"];
for (NSDictionary *dict in arrayOfEntry) {
NSDictionary *title=[dict objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self myTableView]reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//clear background color
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
//set cell text
cell.textLabel.text=[array objectAtIndex:indexPath.row];
//set cell accessory type
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
here we specify the itunes url that we are going to parse and make connection request
- (IBAction)getTop10AlbumAction:(id)sender {
NSURL *url=[NSURL URLWithString:#"http://itunes.apple.com/us/rss/topalbums/limit=10/json"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData=[[NSMutableData alloc]init];
}
[[self myTableView]reloadData];
}
#end
i hope i have made it clear enough!
I suggest you two different tutorials:
Creating a simple interface. Here is a sample from Apple that have a button and a text displayed: iOS Button - Label sample
Insert into controller code (i.e. changeGreeting:) the code that calls the webservice: iOS JSON Webservice tutorial

Resources