Segue item info from CollectionView to ViewController - ios

Good afternoon,
I'm trying to make a Segue when the user touches an item from my CollectionView, but it's not working. First, I get the entries of the user from a database (and they are the full URL of the images) and then I display it in the Collection View.
The problem is, when I try to send the one I have touched, it's always NULL. I have tried following tutorials and examples, but no one is loading the entries from a database (and the full url also). The images are loaded in the "fetchImages".
Can you help me? What do I have to do to send the URL of the item I have touched?
This is my ViewController (where my CollectionView is):
//
#import "ProfileViewController.h"
#import "CarDetailOtherViewController.h"
#import <Security/Security.h>
#import "SSKeychainQuery.h"
#import "SSKeychain.h"
#import "SBJson.h"
#interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
#end
#interface ProfileViewController ()
#end
#implementation ProfileViewController
static NSString * const reuseIdentifier = #"Cell";
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor: [self colorWithHexString:#"FFFFFF"]];
self.profileimage.layer.cornerRadius = self.profileimage.frame.size.width / 2;
self.profileimage.clipsToBounds = YES;
self.profileimage.layer.borderWidth = 1.0f;
self.profileimage.layer.borderColor = [UIColor whiteColor].CGColor;
[self fetchImages];
// COLLECTION VIEW
self.oneCollectionView.dataSource = self;
self.oneCollectionView.delegate = self;
}
// MOSTRAMOS LA INFO CUANDO SE HAYA MOSTRADO EL VIEW
- (void)viewDidAppear:(BOOL)animated
{
[self fetchJson];
}
// COLLECTION VIEW
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 1;
}
// COLLECTION VIEW
-(NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
return 1;
}
// COLLECTION VIEW
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _carImages.count;
}
/*
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
RecipeViewCell *cell = (RecipeViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
recipeImageView.image = [UIImage imageNamed:[recipeImages[indexPath.section] objectAtIndex:indexPath.row]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame-2.png"]];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"photo-frame-selected.png"]];
return cell;
}
*/
// COLLECTION VIEW
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCollectionViewCell *myCell = [collectionView
dequeueReusableCellWithReuseIdentifier:#"MyCell"
forIndexPath:indexPath];
NSString *data = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"];
NSURL * imageURL = [NSURL URLWithString:data];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL: imageURL];
UIImage *img = [UIImage imageWithData:imageData];
[myCell.imageview performSelectorOnMainThread:#selector(setImage:) withObject:img waitUntilDone:YES];
});
return myCell;
}
// PROFILE INFO
-(void)fetchJson {
NSString *usersPassword = [SSKeychain passwordForService:#"login" account:#"account"];
NSLog(#"usersPassword ==> %#", usersPassword);
NSString *post =[[NSString alloc] initWithFormat:#"usersPassword=%#",usersPassword];
//NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://website.com/profile.php"];
//NSData * data = [NSData dataWithContentsOfURL:url];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSInteger stars = [(NSNumber *) [jsonData objectForKey:#"stars"] integerValue];
self.stars.text = [NSString stringWithFormat:#"%li", (long)stars];
NSInteger followers = [(NSNumber *) [jsonData objectForKey:#"followers"] integerValue];
self.followers.text = [NSString stringWithFormat:#"%li", (long)followers];
NSInteger pictures = [(NSNumber *) [jsonData objectForKey:#"photos"] integerValue];
self.pictures.text = [NSString stringWithFormat:#"%li", (long)pictures];
self.username.text = [NSString stringWithFormat:#"*%#", usersPassword];
NSString *picture = [jsonData objectForKey:#"picture"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:picture]];
self.profileimage.image = [UIImage imageWithData:imageData];
}
}
-(void)fetchImages {
self.carImages = [[NSMutableArray alloc] init];
NSString *usersPassword = [SSKeychain passwordForService:#"login" account:#"account"];
NSString * urlString = [NSString stringWithFormat:#"http://website.com/posts.php?usersPassword=%#",usersPassword];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
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];
}
NSLog(#"CARIMAGES ==> %#", _carImages);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// IMAGEN
-(UIColor*)colorWithHexString:(NSString*)hex
{
NSString *cString = [[hex stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) return [UIColor grayColor];
// strip 0X if it appears
if ([cString hasPrefix:#"0X"]) cString = [cString substringFromIndex:2];
if ([cString length] != 6) return [UIColor grayColor];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f)
green:((float) g / 255.0f)
blue:((float) b / 255.0f)
alpha:1.0f];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"segueentry"])
{
NSArray *indexPaths = [self.oneCollectionView indexPathsForSelectedItems];
CarDetailOtherViewController *destViewController = segue.destinationViewController;
NSIndexPath *indexPath = [indexPaths objectAtIndex:0];
destViewController.ID = [[_jsonArray objectAtIndex:indexPath.section] valueForKey:#"imagen"];
NSLog(#"DATA ==> %#", [[_jsonArray objectAtIndex:indexPath.section] valueForKey:#"imagen"]);
}
}
#end
Thanks in advance.

it has to be row instead of section in your prepareforsegue:
destViewController.ID = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"];
and btw: you can easily get the indexpath doing the following:
NSIndexPath *selectedIndexPath = [self.collectionView indexPathForCell:sender];

You have to add this delegate method, this delegate will call every time you select a item in the UICollectionView. Inside this delegate perform your segue. As the sender, send your selected indexPath.
- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"segueentry" sender: indexPath];
}
Then from - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender you can get the selected indexPath as sender for your logic.

Related

appending array with url iOS objective c

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

objective c TableView cell Detail ViewController

My viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
appdataModel = [AppDataModel getInstance];
appdataModel.newsApiUrl = homePagesUrl;
self.view.backgroundColor = [UIColor whiteColor];
NSString *path = [[NSBundle mainBundle] pathForResource:#"contacts" ofType:#"plist"];
contactsArray = [NSArray arrayWithContentsOfFile :path];
[self GetHomePageData];
/**** for left side menu ***/
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sideBarButton setTarget: self.revealViewController];
[self.sideBarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
}
i am getting data from this method :
-(void)GetHomePageData{
// url_to_load = homePagesNews;
NSString *urlString = [NSString stringWithFormat:#"%#",newsApiUrl];
NSURL *url = [[NSURL alloc]initWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
}
for show data in UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier =#"Cell";
CustomCell *customCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
details = res[indexPath.row];
NSString *titleNews = details[#"title"];
NSString *newsDateTime = details[#"datetime"];
NSString *NewsImageName = details[#"featured_image"];
//UIImage *image = [UIImage imageNamed:NewsImageName ];
// UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:NewsImageName]]];
customCell.customFirstNameLabel.text = titleNews;
customCell.customLastnameLabel.text = newsDateTime;
//customCell.customImageView.image =image;
NSURL *imageUrl=[details valueForKey:#"featured_image"];
[customCell.customImageView sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:#"no_image.png"]];
//[tableView reloadData];
return customCell;
}
for show detils data in a tableview after select a cell
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"detailSegue"]) {
//s NSIndexPath *path = Nil;
NSString *titleString = Nil;
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
titleString = [res objectAtIndex:path.row];
[[segue destinationViewController] setTitle:titleString];
}
}
But it's now working . can some help me to solve this ..Thanks in advance
NSString *NewsImageName = details[#"featured_image"]; ,it is dictionary not a string!, you could delete that line.
[details valueForKey:#"featured_image"] it is string, but you are assigning it to NSURL directly.
NSURL *imageUrl=[details valueForKey:#"featured_image"];
replace it as follows
NSURL* imageUrl= [NSURL URLWithString:[details valueForKey:#"featured_image"]];

Unable to retrieve the Data from web service to UITableView

I was Unable to retrieve the data from web service and display the same in my UITableView cell. I was able to see the data that was added in the past. When I go to my application, add a record I was not able to see any thing. Here is the below code. To make sure I was using IOS 8, Xcode 6. I worked on this application in the recent past and use to work fine in IOS 7 or IOS 6. When I upgraded there are few problems like not displaying the data in UITabelView
-(void)loadprojects
{
NSString *eventDate = self.StringfromTextField3;
[[NSUserDefaults standardUserDefaults] setObject:eventDate forKey:#"Eventdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.tableView dataSource]];
NSString *strwebsite = [[NSUserDefaults standardUserDefaults] valueForKey:#"website"];
NSString *websitemethods = #"Timesheet.svc/GetTimesheet";
NSString *projecturltemp = [strwebsite stringByAppendingString:websitemethods];
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#/%#",projecturltemp,usrid,eventDate];
NSURL *url = [NSURL URLWithString:projecturl];
//NSLog(#"url : %#", url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
if(!entries)
{
NSLog(#"Error : %#", error);
}
else{
for (NSDictionary *entry in entries) {
projectNames = [entries valueForKey:#"NM_PROJECT"];
taskNames = [entries valueForKey:#"TASk_NAME"];
subtaskNames = [entries valueForKey:#"SUBTASK_NAME"];
timesheetid = [entries valueForKey:#"ID_TIMESHEET_DTLS"];
projId = [entries valueForKey:#"ID_PROJECT"];
taskId = [entries valueForKey:#"ID_TASK"];
subtaskId = [entries valueForKey:#"ID_SUB_TASK"];
totalhours = [entries valueForKey:#"No_Hours"];
approve = [entries valueForKey:#"FL_APPROVE"];
leaves = [entries valueForKey:#"NM_LEAVE"];
}
}
} else {
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [projectNames count];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identitifier = #"Cell";
TableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier:identitifier
forIndexPath:indexPath];
if ([[[timesheetid objectAtIndex:indexPath.row] stringValue] isEqualToString:#"0"])
{
cell.lblProjects.text = [NSString stringWithFormat:#"%#",#"No Projects Filled"];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Tasks Filled"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No SubTasks Filled"];
cell.lblHours.text = [NSString stringWithFormat:#"%#",#"0 Hours Filled"];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else if ([[leaves objectAtIndex:indexPath.row] isEqualToString:#"0"])
{
cell.lblProjects.text = [projectNames objectAtIndex:indexPath.row];
cell.lblTasks.text = [taskNames objectAtIndex:indexPath.row];
cell.lblSubTasks.text = [subtaskNames objectAtIndex:indexPath.row];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
NSLog(#"cell :%#",cell.lblHours.text);
NSLog(#"lblProjects :%#",cell.lblProjects.text);
}
else
{
cell.lblProjects.text = [leaves objectAtIndex:indexPath.row];
cell.lblTasks.text = [NSString stringWithFormat:#"%#",#"No Projects/Tasks on this Date"];
cell.lblSubTasks.text = [NSString stringWithFormat:#"%#",#"No Sub Tasks on this Date"];
cell.lblHours.text = [[totalhours objectAtIndex:indexPath.row] stringValue];
}
cell.editingAccessoryType = UITableViewCellAccessoryDetailDisclosureButton;
NSNumber *myProjectArrayString = [timesheetid objectAtIndex:indexPath.row];
cell.hdbrowcount = [NSString stringWithFormat:#"%#",myProjectArrayString];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSLog(#"index :%#",[timesheetid objectAtIndex:[self.tableView indexPathForSelectedRow].row]);
[self performSegueWithIdentifier:#"segueName" sender:indexPath];
//[tableView setEditing:YES animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"segueNameforAddPage"])
{
UINavigationController *segueNameNavController=segue.destinationViewController;
AddProjectDetails *NavWeekScreen = (AddProjectDetails*)segueNameNavController.topViewController;
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NavWeekScreen.projidstocancel = self.StringfromTextField3;
NavWeekScreen.StringfromProjectsTasksscreenuser=str;
NSInteger appoved = [[approve valueForKeyPath:#"#sum.integerValue"] intValue];
NavWeekScreen.ApprovalorNot = appoved;
NSInteger sumArray = [[totalhours valueForKeyPath:#"#sum.integerValue"] floatValue];
NavWeekScreen.totalhrsAdd = sumArray;
}
}

Putting data from SONObjectWithData to UITableView

i am building a app in which i am getting data from a php file and already NSLoging it in xcode and it is showing data in this format:
jsonObject=(
(
1,
abc,
"abc#xyz.com",
"501 B3 Town"
),
(
2,
sam,
"sam#xyz.com",
"502 B3 Town"
),
(
3,
jhon,
"jhon#xyz.com",
"503 B Town"
)
)
and here is my viewdidload
- (void)viewDidLoad
{
[super viewDidLoad];
statuses=[[NSMutableArray alloc]init];
NSURL *myURL = [NSURL URLWithString:#"http://url/result.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#",jsonObject);
statuses = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}];
}
now i want to display all records in uitableview. can anyone tell me how can i do that. Thanks
check this tutorial out:
http://thedarkdev.blogspot.co.uk/2013/09/web-service-apps-in-ios7-json-with.html
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return myObject.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Item";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[[UITableViewCell alloc]initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *text;
//text = [NSString stringWithFormat:#"%#",[tmpDict objectForKey:title]];
text = [NSMutableString stringWithFormat:#"%#",
[tmpDict objectForKeyedSubscript:title]];
NSMutableString *detail;
detail = [NSMutableString stringWithFormat:#"Author: %# ",
[tmpDict objectForKey:author]];
NSMutableString *images;
images = [NSMutableString stringWithFormat:#"%# ",
[tmpDict objectForKey:thumbnail]];
NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc]initWithData:data];
cell.textLabel.text = text;
cell.detailTextLabel.text= detail;
cell.imageView.frame = CGRectMake(0, 0, 80, 70);
cell.imageView.image =img;
return cell;
}
I This format is Array -> Array format in inner array may count is consistent (4) elements
Try This onece
No of row in Sections method take - jsonparsingarray count
Cell for row at index method
display like this ex: name and email id that index is 1 & 3
if ([[jsonparsingarray objectatindex:indexpath.row] count])
{
cell.textlable.text = [[jsonparsingarray objectatindex:indexpath.row]objectatindex:1];
cell.detailtextlable.text = [[jsonparsingarray objectatindex:indexpath.row]objectatindex:3];
}

Cell text overlapping when scrolling in UITableView Xcode iOS

Everytime I start scrolling in the tableView the subtitleLabel text keeps overlapping each other in every row. I've tried for the last 4 hours every single search on the Internet for this problem I have clicked and tried.
Here is my ViewController.m:
#interface ANViewController()
{
NSMutableArray *TitleLabel;
NSMutableArray *SubtitleLabel;
NSMutableArray *AvatarImages;
}
#end
#implementation ANViewController
#synthesize thetableview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.thetableview.delegate = self;
self.thetableview.dataSource = self;
TitleLabel = [NSMutableArray array];
SubtitleLabel = [NSMutableArray array];
AvatarImages = [NSMutableArray array];
__block NSArray *posts;
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSError *error;
NSMutableDictionary *allNews = [NSJSONSerialization JSONObjectWithData:allNewsData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
posts = allNews[#"data"];
for (NSDictionary *newsPost in posts) {
[TitleLabel addObject:newsPost[#"title"]];
[SubtitleLabel addObject:newsPost[#"post_message"]];
NSString *avatarUrl = AVATAR_URL;
NSString *avatarExt = #".jpg";
[AvatarImages addObject:[NSString stringWithFormat:#"%#%#%#", avatarUrl, newsPost[#"user_id"], avatarExt]];
}
}
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
long count = TitleLabel.count;
if(count == 0){
count = 1;
}
return count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier;
ANTableViewCell *Cell;
if(TitleLabel.count == 0){
NSLog(#"Did with no news");
CellIdentifier = #"Cell_NoNews";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.noNewsLabel.text = #"No news to display!";
}else{
NSLog(#"Did with news");
CellIdentifier = #"Cell";
Cell = [thetableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (Cell == nil) {
Cell = [[ANTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.TitleLabel.text = [TitleLabel objectAtIndex:indexPath.row];
Cell.SubtitleLabel.text = [SubtitleLabel objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[AvatarImages objectAtIndex:indexPath.row]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
Cell.AvatarImage.image = img;
}
return Cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
Just change UITableViewCellStyleSubtitle for UITableViewCellStyleDefault, and you need an asynchronous connection instead of a synchronous like you're doing: NSData *allNewsData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:API_URL]]; in your viewDidLoad method that is blocking your main thread.
You can adapt this code to your need, in order to download it on the background:
__block NSData *allNewsData = nil;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
allNewsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: API_URL]];
NSURL *url = [NSURL URLWithString: WEBSITE_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[webView loadRequest:urlRequest];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(#"THIS IS THE MAIN THREAD...");
[self.thetableview reloadData];
});
});

Resources