define the UITableViewCell out of Storyboard with NIB - ios

I used the Json array to show data from server.
when I change the CellIdentifier to #Cell which i used in CellIdentifier the pushDetailView is working and it's going to next page but when I change to CustomCell again just show the name of city and state in first page and when i click on that doesnt go to next page. the reason I need the #CustomCell because I need 2 labels view in first page and when I change it to #cell it just show one label.
Thank you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
City * cityObject;
cityObject = [ citiesArry objectAtIndex:indexPath.row];
cell.textLabel.text = cityObject.cityState;
cell.detailTextLabel.text = cityObject.cityPopulation;
cell.detailTextLabel.numberOfLines = 4;
//NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://mobileapps.binaryappdev.com/applelogo.png"] ];
//[[cell imageView] setImage:[UIImage imageWithData:imageData] ];
return cell;
}
#pragma mark - Navigation
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"pushDetailView"])
{
NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
City * object = [citiesArry objectAtIndex: indexPath.row];
[[segue destinationViewController] getCity:object];
}
}
#pragma mark -
#pragma mark Class Methods
-(void) retrievedData;
{
NSURL * URL = [ NSURL URLWithString:getDataURL];
NSData * data = [ NSData dataWithContentsOfURL:URL];
jsonArry = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:Nil];
//city
citiesArry = [[NSMutableArray alloc] init];
//loop
for (int i=0; i<jsonArry.count; i++) {
NSString * cID = [[ jsonArry objectAtIndex:i] objectForKey:#"id"];
NSString * cName = [[ jsonArry objectAtIndex:i] objectForKey:#"cityName"];
NSString * cState = [[ jsonArry objectAtIndex:i] objectForKey:#"cityState"];
NSString * cCountry = [[ jsonArry objectAtIndex:i] objectForKey:#"country"];
NSString * cPopulation = [[ jsonArry objectAtIndex:i] objectForKey:#"cityPopulation"];
NSString * cImage = [[ jsonArry objectAtIndex:i] objectForKey:#"cityImage"];
[citiesArry addObject:[[City alloc] initWithcityName:cName andcityState:cState andcityCountry:cCountry andcityPopulation:cPopulation andcityImage:cImage andcityID:cID ]];
}
[self.tableView reloadData];
}
#end
DetailViewController
#synthesize cityNameLabel, stateLabel, countryLabel, populationLabel, currentCity;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setLabels];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark Class Methods
-(void) getCity:(id)cityObject
{
currentCity = cityObject;
}
-(void) setLabels
{
cityNameLabel.text= currentCity.cityName;
countryLabel.text = currentCity.cityCountry;
stateLabel.text = currentCity.cityState;
populationLabel.text = currentCity.cityPopulation;
cityNameLabel.numberOfLines= 0;
}
#end

if you don´t have segue for your customcell when you push in a cell your method didSelectRow:AtIndexPath will be called. You can do yourself a pushViewController from that method or [self performSegueWithIdentifier: #"pushDetailView" sender: self];

Related

How to resolve when UITableview is double open on same page

I have 2 UITableView. On first UITableView make for search and select cell. After selected cell from UITableView1. It's will show blank data of UITableView2 and show new UITableView2 again with data.
I'm sorry for my bad english language.
I can speak english a little bit.
If you don't understand my question.
Please follow to see pictures below here.
First UITableView: (Click button for go to second UITableView.)
After click button. UITableView2 show blank data.
And auto show new UITableView2 with data again.
UITableView1
#interface SearchByContainerDetailViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableViewWhereHoseList;
#end
#implementation SearchByContainerDetailViewController
#synthesize labelName,strName,txResult,strResult,labelStatus;
NSString *selectedWhereHouse;
GlobalVariable *gloablOnWherehouse;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
labelName.text = strName;
//txResult.text = strResult;
labelStatus.text = #"NULL";
gloablOnWherehouse = [GlobalVariable sharedInstance];
gloablOnWherehouse.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
}
- (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 (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"%lu", (unsigned long)[gloablOnWherehouse.arTableDataSelected count]);
return (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SearchByContainerDetailViewCell";
SearchByContainerDetailViewCell *cell = [self.tableViewWhereHoseList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SearchByContainerDetailViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (gloablOnWherehouse.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:gloablOnWherehouse.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [gloablOnWherehouse.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_Detail"];
NSString *date = [self getString:[cont objectForKey:#"date"]];
NSString *qty = [self getString:[cont objectForKey:#"qty"]];
NSString *stock = [self getString:[cont objectForKey:#"stock"]];
NSString *ord = [self getString:[cont objectForKey:#"ord"]];
NSString *custmr = [self getString:[cont objectForKey:#"custmr"]];
NSString *remarks = [self getString:[cont objectForKey:#"remarks"]];
NSString *invoice = [self getString:[cont objectForKey:#"invoice"]];
NSString *due = [self getString:[cont objectForKey:#"due"]];
NSString *lot = [self getString:[cont objectForKey:#"lot"]];
NSString *gap = [self getString:[cont objectForKey:#"gap"]];
[cell setDate:date setQty:qty setStock:stock setOrd:ord setCustmr:custmr setRemarks:remarks setInvoice:invoice setDue:due setLot:lot setGap:gap];
}
}
}
return cell;
}
- (void) requestEWIServiceFinish:(EWIConnector *)connector responseData:(NSDictionary *)responseData{
NSLog(#"finish %#",connector.serviceName);
NSLog(#"response %#",responseData);
if ([connector.serviceName isEqualToString:#"special_selected_f10"])
{
NSLog(#"finish %#",connector.serviceName);
NSDictionary *content = responseData[#"content"];
NSString *stAlertMes = [content objectForKey:#"alertMessage"];
stAlertMes = [self getString:stAlertMes];
NSLog(#"AlertMSG : %#", stAlertMes);
if (![stAlertMes isEqualToString:#""]) {
NSLog(#"ALERT MESSAGE : %#", stAlertMes);
gloablOnWherehouse.arTableDataSelected = [[NSArray alloc] init];
}
else
{
NSLog(#"HAS DATA");
gloablOnWherehouse.arTableDataSelected = [content objectForKey:#"DataList_SPI_DetailCollection"];
[self.tableViewWhereHoseList reloadData];
labelStatus.text = #"F11";
}
}
else
{
NSLog(#"response %#",responseData);
}
}
- (void) requestEWIServiceFail:(EWIConnector *)connector error:(NSError *)error{
NSLog(#"request fail %#",connector);
}
- (NSString *)getString:(NSString *)string
{
return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (IBAction)btnf10
{
NSMutableDictionary *content = [NSMutableDictionary dictionary];
[content setValue:[[AppSetting sharedInstance] token] forKey:#"ewitoken"];
//[content setValue:gloablOnWherehouse.selectedWhereHouse forKey:#"model_Name"];
[[EWIConnector connector] requestEWIService:#"special_selected_f10" requestData:content delegate:self];
}
UITableView2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
globlOnDisplayEffect = [GlobalVariable sharedInstance];
globlOnDisplayEffect.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
[self.tableViewDetailList reloadData];
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (globlOnDisplayEffect.arTableDataSelected)?[globlOnDisplayEffect.arTableDataSelected count]: 1;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"DisplayEffectQtyViewCell";
DisplayEffectQtyViewCell *cell = [self.tableViewDetailList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DisplayEffectQtyViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (globlOnDisplayEffect.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:globlOnDisplayEffect.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [globlOnDisplayEffect.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_DetailF10"];
NSString *f10_cmpt = [self getString:[cont objectForKey:#"f10_cmpt"]];
NSString *f10_dt = [self getString:[cont objectForKey:#"f10_dt"]];
NSString *f10_item = [self getString:[cont objectForKey:#"f10_item"]];
NSString *f10_lot = [self getString:[cont objectForKey:#"f10_lot"]];
NSString *f10_model = [self getString:[cont objectForKey:#"f10_model"]];
NSString *f10_of = [self getString:[cont objectForKey:#"f10_of"]];
NSString *f10_semi = [self getString:[cont objectForKey:#"f10_semi"]];
NSString *f10_tm = [self getString:[cont objectForKey:#"f10_tm"]];
NSString *f10_uncmp = [self getString:[cont objectForKey:#"f10_uncmp"]];
[cell setf10_cmpt:f10_cmpt setf10_dt:f10_dt setf10_item:f10_item setf10_lot:f10_lot setf10_model:f10_model setf10_of:f10_of setf10_semi:f10_semi setf10_tm:f10_tm setf10_uncmp:f10_uncmp];
}
}
}
return cell;
}
- (void) requestEWIServiceStart:(EWIConnector *)connector{
NSLog(#"start %#",connector.endpoint);
}
TO Check if view controller already push or not.
if(![self.navigationController.topViewController isKindOfClass:[NewViewController class]]) {
[self.navigationController pushViewController:newViewController animated:YES];
}

Grouped Tableview From JSON Data

I've been following a tutorial on YouTube and trying to expand its functionality. I figured out how to send the retrieveData method to a background thread using GCD, figured out how to use Reachability to keep the app from crashing when in Airplane Mode, and now I'm trying to change the tableview to a grouped style. After a couple of weeks I'm at my wit's end.
What I want to do is have the UITableView grouped using the key "country" to establish the groups, and any city within that country appear in the group's cells. The number of countries in the database will change, as will the number of cities.
I'm not even sure it's possible given the data structure, but if it is, I could use some suggestions.
The JSON data is structured like this:
[{"id":"1","cityName":"London","cityState":"London","cityPopulation":"8173194","country":"United Kingdom"}
Here is the .m file:
#import "CitiesViewController.h"
#import "City.h"
#import "DetailViewController.h"
#import "Reachability.h"
#define getDataUrl #"http://www.conkave.com/iosdemos/json.php"
#interface CitiesViewController ()
#end
#implementation CitiesViewController
#synthesize jsonArray, citiesArray;
- (void)viewDidLoad {
[super viewDidLoad];
//Set the title of our VC
self.title = #"Cities of the World";
//Load data
[self retrieveData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (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 citiesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
City * cityObject;
cityObject = [citiesArray objectAtIndex:indexPath.row];
cell.textLabel.text = cityObject.cityName;
cell.detailTextLabel.text = cityObject.cityCountry;
//Accessory
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if ([[segue identifier] isEqualToString:#"pushDetailView"])
{
NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
//Get the object for the selected row
City * object = [citiesArray objectAtIndex:indexPath.row];
[[segue destinationViewController] getCity:object];
}
}
#pragma mark -
#pragma mark Class Methods
- (void) retrieveData;
{
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable) {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"No Internet"
message:#"You must have an internet connection for this feature"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
[self.refreshControl endRefreshing];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return;
}
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
//Retrieve the data asynchronously
dispatch_async(queue, ^{
NSURL * url = [NSURL URLWithString:getDataUrl];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Set up our cities array
citiesArray = [[NSMutableArray alloc] init];
//Loop through our jsonArray
for (int i = 0; i < jsonArray.count; i++)
{
//Create our city object
NSString * cID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * cName = [[jsonArray objectAtIndex:i] objectForKey:#"cityName"];
NSString * cState = [[jsonArray objectAtIndex:i] objectForKey:#"cityState"];
NSString * cPopulation = [[jsonArray objectAtIndex:i] objectForKey:#"cityPopulation"];
NSString * cCountry = [[jsonArray objectAtIndex:i] objectForKey:#"country"];
//Add the city object to our cities array
[citiesArray addObject:[[City alloc] initWithCityName:cName andCityState:cState andCityCountry:cCountry andcityPopulation:cPopulation andCityID:cID]];
}
//Back to main thread to update UI.use dispatch_get_main_queue() to get main thread
dispatch_sync(dispatch_get_main_queue(), ^{
//Reload our table view
[self.tableView reloadData];
});
});
}
#end
You can group the data yourself pretty easily in a few ways. One way is by using an array for ordering the countries and a dictionary to group the cities within them.
After you are done creating your City objects, you can do something like this:
// you probably want to save these as instance properties
NSMutableArray *countries = [NSMutableArray new];
NSMutableDictionary *citiesForCountries = [NSMutableDictionary new];
for(City *city in citiesArray)
{
NSString *currentCountry = city.country;
NSMutableArray *citiesInCountry = citiesForCountries[#"currentCountry"];
// first city for this country, so add it to our ordered list and create an array to populate with cities
if(! citiesInCountry)
{
[countries addObject:currentCountry];
citiesInCountry = [NSMutableArray new];
citiesForCountries[#"currentCountry"] = citiesInCountry;
}
[citiesInCountry addObject:city];
}
// Then here are some of the relevant methods on how you would use these data structures
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return countries.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *country = countries[section];
NSArray *cities = citiesForCountries[country];
return cities.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
City * cityObject;
NSString *country = countries[indexPath.section];
NSArray *cities = citiesForCountries[country];
cityObject = cities[indexPath.row];
cell.textLabel.text = cityObject.cityName;
cell.detailTextLabel.text = cityObject.cityCountry;
//Accessory
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}

Segue not updated inside TableViewController

Good afternoon,
I have created a Segue in my TableViewController where the user can touch the user profile and it sends that username to a ProfileViewController, where the user information is loaded (posts, image, info...) (something like a Facebook wall).
The problem is when I touch one user, it displays everything correctly, but when I touch another profile image, it displays the same ProfileViewController again, like the username is not updated and it's send wrong.
When I touch anywhere on the screen and then I touch again the user profile, in that case it works, but I need to make this work in every case.
I'm going to post my TableViewController if that helps you to find the problem because it's almost working, the only thing that I need to fix is that username that is not updated (Tap Gesture Recognizer over the image).
The segues are at the end of the code.
TableViewController.m
//
// CarTableViewController.m
//
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import "OtherProfileUserViewController.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];
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = YES;
}
- (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:#"imagen"] 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)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://website.com/service.php"];
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];
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];
}
NSLog(#"carModels ==> %#", _jsonArray);
dispatch_async(dispatch_get_main_queue(), ^{
{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}});
}
);
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"segueprofile"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
if ([segue.identifier isEqualToString:#"segueprofile2"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
}
}
#end
Thanks in advance.
OK, here is one of the options.
1. Delete all existing segues (segueprofile and segueprofile2)
2. Connect your tableviewcontroller (important: not tableview but controller itself) with your details controller by push-segue and name it segueprofile3
3. Refactor your code in the following manner
#property (nonatomic, strong) NSIndexPath * selectedIndexPath;
...
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)anIndexPath {
self.selectedIndexPath = anIndexPath;
[self performSegueWithIdentifier:#"segueprofile3" sender:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"segueprofile3"]) {
OtherProfileUserViewController *destViewController = segue.destinationViewController;
destViewController.recipeName = [[_jsonArray objectAtIndex:selectedIndexPath.row] valueForKey:#"username"];
}
}
Another option. Place UIButton control right over avatar UIImageView. Create associated IBOutlet inside your CarTableViewCell class and make outlet connection.
#property (nonatomic, weak) UIButton * btnAvatar;
Next, modify CarTableViewController code
//1. declare new propery
#property (nonatomic, strong) id selectedProfile;
//2. implement future button tap handler
-(IBAction) btnAvatarDidPress:(id) sender {
int tag = ((UIButton *) sender).tag;
self.selectedProfile = [_jsonArray objectAtIndex:tag];
[self performSegueWithIdentifier:#"segueprofile3" sender:nil];
}
//Extend your cellForRowAtIndexPath method
- (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.btnAvatar.tag = indexPath.row;
... rest of method
}
then remove didSelectRowAtIndexPath method, and connect btnAvatar Touch Up Inside action to btnAvatarDidPress method inside your controller code.
That's all I hope I've forgot nothing.
here is your example, in prepareForSegue, get the cell which button is in:
id v = sender;
while (![(v= v.superView) isKindOfClass:[UITableViewCell class]]
&& v!=nil) ;
if (v==nil)
// no ancestor view is cell.
else{
// now v is the cell.
NSIndexPath * indexPath = [self.tableView indexPathForCell:v];
// do the left
}

Pull to refresh UITableView Data

I have a pull to refresh setup. It's currently calling [self.tableView reloadData]; but It's not reloading my parsed Json data from the blogData method. Is theres something I'm missing?
My controller is like this:
//
// ARTableViewController.m
// WorldCupLive
//
// Created by Adam Rais on 14/06/2014.
// Copyright (c) 2014 Adam Rais. All rights reserved.
//
#import "ARTableViewController.h"
#import "ARModal.h"
#interface ARTableViewController ()
#end
#implementation ARTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.blogPost = [[ARModal alloc] init];
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
[self randomBackgroundImage];
self.tableView.contentInset = UIEdgeInsetsMake(0.0f, -10.0f, 0.0f, 0.0f);
// Initialize Refresh Control
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
// Configure Refresh Control
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
// Configure View Controller
[self setRefreshControl:refreshControl];
}
-(void)randomBackgroundImage {
UIImage *image = self.blogPost.imageUI;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
self.tableView.backgroundView = imageView;
self.tableView.backgroundView.layer.zPosition -= 1;
}
- (void)refresh:(id)sender
{
NSLog(#"Refreshing");
[self.tableView reloadData];
[self randomBackgroundImage];
// End Refreshing
[(UIRefreshControl *)sender endRefreshing];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (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 [self.blogPost.jsonMutable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// Configure the cell...
ARModal *post = [self.blogPost.jsonMutable objectAtIndex:indexPath.row];
NSData *imageData = [NSData dataWithContentsOfURL:post.jsonURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.textLabel.text = [[[[[post.home stringByAppendingString:#" "]stringByAppendingString:#" "] stringByAppendingString:post.bst] stringByAppendingString:#" "] stringByAppendingString:post.away];
cell.detailTextLabel.text = post.info;
cell.imageView.image = image;
cell.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.000];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
And my modal:
//
// ARModal.m
// WorldCupLive
//
// Created by Adam Rais on 14/06/2014.
// Copyright (c) 2014 Adam Rais. All rights reserved.
//
#import "ARModal.h"
#implementation ARModal
-(id)initWithHome:(NSString *)home {
self = [super init];
if (self) {
_home = home;
_away = nil;
_result = nil;
_info = nil;
_homeImage = nil;
}
return self;
}
+(id)blogPostWithHome:(NSString *)home {
return [[self alloc] initWithHome:home];
}
-(NSArray *)blogData {
NSURL *jsonURL = [NSURL URLWithString:#"http://www.kimonolabs.com/api/2nfgfo2s?apikey=1a1f5f323969d5157af8a8be857026c2"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *jsonError = nil;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];
NSArray *jsonArray = [[jsonDictionary objectForKey:#"results"] objectForKey:#"collection1"];
if (blogData == nil) {
blogData = jsonArray;
}
return blogData;
}
-(NSURL *)jsonURL {
return [NSURL URLWithString:self.homeImage];
}
-(NSString *)bst {
NSString *sentence = self.result;
NSString *word = #"-";
NSString *wordTwo = #"00.00";
NSString *wordThree = #"01.00";
NSMutableArray *bstArray = [NSMutableArray array];
if ([sentence rangeOfString:word].location != NSNotFound) {
NSLog(#"Found the string");
[bstArray addObject:sentence];
} else if ([sentence rangeOfString:wordTwo].location != NSNotFound) {
NSLog(#"time is 23:00");
[bstArray addObject:#"23:00"];
} else if ([sentence rangeOfString:wordThree].location != NSNotFound) {
NSLog(#"time is 00:00");
[bstArray addObject:#"00:00"];
} else {
float floatOne = [sentence floatValue];
float floatFinal = floatOne - 1.000000;
NSString *str = [NSString stringWithFormat:#"%f", floatFinal];
NSString *bstFinal = [str substringToIndex:[str length] - 4];
[bstArray addObject:bstFinal];
}
return [bstArray objectAtIndex:0];
}
-(UIImage *)imageUI {
NSArray *imageArray = #[[UIImage imageNamed:#"Algeria"],[UIImage imageNamed:#"Argentina"],[UIImage imageNamed:#"Australia"],[UIImage imageNamed:#"Belgium"],[UIImage imageNamed:#"Bosnia-Herzegovina"],[UIImage imageNamed:#"Switzerland"],[UIImage imageNamed:#"Uruguay"],[UIImage imageNamed:#"USA"],[UIImage imageNamed:#"Brazil"],[UIImage imageNamed:#"Cameroon"],[UIImage imageNamed:#"Chile"],[UIImage imageNamed:#"Colombia"],[UIImage imageNamed:#"Costa Rica"],[UIImage imageNamed:#"Côte d'Ivoire"],[UIImage imageNamed:#"Croatia"],[UIImage imageNamed:#"Ecuador"],[UIImage imageNamed:#"England"],[UIImage imageNamed:#"France"],[UIImage imageNamed:#"Germany"],[UIImage imageNamed:#"Ghana"],[UIImage imageNamed:#"Greece"],[UIImage imageNamed:#"Honduras"],[UIImage imageNamed:#"Iran"],[UIImage imageNamed:#"Italy"],[UIImage imageNamed:#"Japan"],[UIImage imageNamed:#"Mexico"],[UIImage imageNamed:#"Netherlands"],[UIImage imageNamed:#"Nigeria"],[UIImage imageNamed:#"Portugal"],[UIImage imageNamed:#"Russia"],[UIImage imageNamed:#"South Korea"],[UIImage imageNamed:#"Spain"]];
int random = arc4random_uniform(imageArray.count);
return [imageArray objectAtIndex:random];
}
#end
When you call the -[UITableView reloadData] method you are telling the tableview to refresh ints content based on the source you already gave him, but he doesnt change the source. In some cases you refresh you datasource and you need to refresh the UITableView so you call the -[UITableView reloadData]. What you need to do is to first refresh you data and the refresh the view, so the view uses your new data.
Use the the same way you got the data from your modal to refresh it.
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
Then execute the -[UITableView reloadData], but now he is going to refresh using the refreshed data that you got from your modal.
If you need something else, comment.
-[UITableView reloadData] doesn't actually reload your data. It tells the table that you've reloaded the data, and now you need the table view to reload.
So before you call reloadData you should do:
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
Also as this chunk of code only uses information provided by ARModal, you should probably put it in a method in ARModal

Can NOT segue between Storyboards

So I found a nice outline that gives me what I want. However, I can't switch to other storyboards?
How do I segue into other storyboards with a 'built in' window?
Included is my ViewController.M implementation file. This code seems to make a table on its own instead of use the storyboard (navigation controller)...
How do I make it work to segue to other storyboards?
#import "ViewController.h"
#interface ViewController ()
#end
#define getDataURL #"http://??.??.??.??/phpfile12.php"
#implementation ViewController
#synthesize json, storesArray, myTableView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationController.navigationBar.titleTextAttributes = #{NSForegroundColorAttributeName : [UIColor whiteColor]};
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;
self.navigationController.view.backgroundColor = [UIColor clearColor];
//set the title
self.title = #"";
[self retrieveData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return storesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
//cell.textLabel.text = [NSString stringWithFormat:#"Cell %d", indexPath.row];
//Retrieve the current city object for use with this indexPath.row
Store * currentStore = [storesArray objectAtIndex:indexPath.row];
cell.textLabel.text = currentStore.storeName;
cell.detailTextLabel.text = currentStore.storeAddress;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark - UITableView Delegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController * dvc = [[DetailViewController alloc]init];
//Retrieve the current selected city
Store * currentStore = [storesArray objectAtIndex:indexPath.row];
dvc.name = currentStore.storeName;
dvc.address = currentStore.storeAddress;
dvc.startDate = currentStore.storeStartDate;
dvc.endDate = currentStore.storeEndDate;
dvc.startTime = currentStore.storeStartTime;
dvc.endTime = currentStore.storeEndTime;
dvc.totalSales = currentStore.storeTotalSales;
dvc.voids = currentStore.storeVoids;
dvc.discounts = currentStore.storeDiscounts;
dvc.guestCount = currentStore.storeGuestCount;
dvc.peopleServed = currentStore.storePeopleServed;
dvc.employeeClockIn = currentStore.storeEmployeeClockIn;
[self.navigationController pushViewController:dvc animated:YES];
}
#pragma mark - Methods
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Set up our cities array
storesArray = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
//Create city object
NSString * sID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString * sAddress = [[json objectAtIndex:i] objectForKey:#"storeAddress"];
NSString * sName = [[json objectAtIndex:i] objectForKey:#"storeName"];
NSString * sStartDate = [[json objectAtIndex:i] objectForKey:#"storeStartDate"];
NSString * sStartTime = [[json objectAtIndex:i] objectForKey:#"storeStartTime"];
NSString * sEndDate = [[json objectAtIndex:i] objectForKey:#"storeEndDate"];
NSString * sEndTime = [[json objectAtIndex:i] objectForKey:#"storeEndTime"];
NSString * sTotalSales = [[json objectAtIndex:i] objectForKey:#"storeTotalSales"];
NSString * sVoids = [[json objectAtIndex:i] objectForKey:#"storeVoids"];
NSString * sDiscounts = [[json objectAtIndex:i] objectForKey:#"storeDiscounts"];
NSString * sGuestCount = [[json objectAtIndex:i] objectForKey:#"storeGuestCount"];
NSString * sPeopleServed = [[json objectAtIndex:i] objectForKey:#"storePeopleServed"];
NSString * sEmployeeClockIn = [[json objectAtIndex:i] objectForKey:#"storeClockIn"];
Store * myStore = [[Store alloc]initWithStoreID: (NSString *) sID andStoreName: (NSString *) sName andStoreStartDate: (NSString *) sStartDate andStoreStartTime: (NSString *) sStartTime andStoreEndDate: (NSString *) sEndDate andStoreEndTime: (NSString *) sEndTime andStoreTotalSales: (NSString *) sTotalSales andStoreVoids: (NSString *) sVoids andStoreDiscounts: (NSString *) sDiscounts andStoreGuestCount: (NSString *) sGuestCount andStorePeopleServed: (NSString *) sPeopleServed andStoreEmployeeClockIn: (NSString *) sEmployeeClockIn andStoreAddress: (NSString *) sAddress];
//Add our city object to our cities array
[storesArray addObject:myStore];
}
[self.myTableView reloadData];
}
#end
To instantiate a view controller from another storyboard you can use UIStoryboard storyboardWithName
UIViewController *dvc = [[UIStoryboard storyboardWithName:#"yourStoryboardName" bundle:nil] instantiateViewControllerWithIdentifier:#"yourViewIdentifier"];
[self.navigationController pushViewController:dvc animated:YES];
This is more a general answer, though.
I don't understand what you exactly asking but for simple segue i used this line of code
[self performSegueWithIdentifier:#"identifier" sender:self];
if you want to segue without linking than you have to give identifier to view controller and use this code below
UIViewController *homeViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"identifier"];
[self presentViewController:homeViewController animated:0 completion:nil];
I am not entire sure what you mean by "Segue to other storyboard"? The following code allows you to jump to a totally different view controller tree inside the same storyboard by a click of button or other action.
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *initViewController = [storyboard instantiateViewControllerWithIdentifier:#"SecondScreen"];
delegate.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
delegate.window.rootViewController = initViewController;
[delegate.window makeKeyAndVisible];
Main is the name of your storyboard that you want to jump into.
SecondScreen is the storyboard ID of the view controller. Most likely it is a navigation or a container. You will need to set "SecondScreen" under identity inspector.

Resources