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;
}
}
Related
I am new to IOS i need to create parameter for POST method using picker view did select row.
Picker view did select row:
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if(pickerView.tag ==2){
txtText.text = (NSString *)[arrMsg objectAtIndex:row];
NSLog([arrmsg1 objectAtIndex:row]);
}else if(pickerView.tag ==1){
currency1.text = (NSString *)[currencyname1 objectAtIndex:row];
NSLog([id1 objectAtIndex:row]);
}
else
{
currency2.text = (NSString *)[from_currency objectAtIndex:row];
NSLog([id2 objectAtIndex:row]);
}
}
post method:
here str is considered as parameter for post method but i struggling how to call picker view did select row array as my parameter str.
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[str length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
NSLog(#"%#",str);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
mutableData = [[NSMutableData alloc]init];
}
}
viewdidload:
coding :
- (void)viewDidLoad {
[super viewDidLoad];
NSString *parseURL =#"Url1";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json valueForKeyPath:#"Branches.branch_name"];
//NSLog(#"%#",json);
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
firststr = [arrmsg1 componentsJoinedByString:#","];
NSLog(#"%#",arrmsg1);
arrMsg.count!=0;
if (arrMsg.count >0)
{
txtText.text = (NSString *)[arrMsg objectAtIndex:0];
}
}
//second textfield and third textfield
NSString *parseURL1 =#"url2";
NSString *encodeurl1 =[parseURL1 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url1 = [NSURL URLWithString:encodeurl1];
NSData *data1 = [NSData dataWithContentsOfURL:url1];
if(data1){
NSError *error1;
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:data1 options: kNilOptions error:&error1];
//NSLog(#"%#",json1);
currencyname1 = [json1 valueForKeyPath:#"Currencies.currency_name"];
id1 = [json1 valueForKeyPath:#"Currencies.id"];
NSLog(#"%#",id1);
from_currency = [json1 valueForKeyPath:#"Currencies.currency_name"];
id2 = [json1 valueForKeyPath:#"Currencies.id"];
secondstr = [id1 componentsJoinedByString:#","];
thirdstr = [id2 componentsJoinedByString:#","];
NSLog(#"%#",secondstr);
NSLog(#"%#",thirdstr);
//NSLog(#"%#",json1);
currencyname1.count!=0;
if (currencyname1.count >0)
{
currency1.text = (NSString *)[currencyname1 objectAtIndex:0];
}
from_currency.count!=0;
if (from_currency.count >0)
{
currency2.text = (NSString *)[from_currency objectAtIndex:0];
}
}
str = [NSString stringWithFormat:#"branch_id=%#&from_curr=%#&to_curr=%#&value=%#",firststr,secondstr,thirdstr,fourthstr];
pktStatePicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
pktStatePicker .delegate = self;
pktStatePicker .dataSource = self;
txtText.delegate = self ;
currency1.delegate = self;
currency2.delegate = self;
[ pktStatePicker setShowsSelectionIndicator:YES];
You should set tag to your text fields.
Then on button click you can get text of your textfields and call sendDataToServer method from this button click not from did select row.
Hope this will help :)
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.
I had some data in my UITableView with four labels (Project,tasks, subtasks and hours), I changed my data from the backend (going to database and changed the data). I changed number of hours from 12 to 10. But I was only seeing the old data (12 hours instead of 10 hours) in my UITableView. Can any one suggest what is the reason behind that. I tried to clean, restart the computer which doesn't load the correct data that is in database. Other thing I can add is I was retrieving the data with the help of web service. and converting the data from JSONSerialization format to NSArray. When I ping my web service in browser URL, it gives me the correct data. Here is the below code :
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadprojects];
}
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];
[self.tableView reloadData];
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];
//NSLog(#"urlData : %#",urlData);
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 *responseDatatest = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments error:&error];
NSLog(#"responseDatatest : %#",responseDatatest);
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[responseDatatest dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
NSLog(#"Entries : %#", entries);
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 {
}
- (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);
}
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;
}
I don't see this line
[self.tableview reloadData];
use postnotification whenever change data.
[[NSNotificationCenter defaultCenter] postNotificationName:#"refresh" object:self];
in viewDidLoad
{
[super viewDidLoad];
postjson = [[PostJson alloc] init];
[postjson startpost];
_table = [[UITableView alloc] init];
FOOTPRINT;
_table.delegate = self;
_table.dataSource =self;
[self.view addSubview:_table];
}
in startpost
-(NSMutableArray*)startpost:(NSString *)title category_id:(NSString *)category_id limits:(NSNumber *)limits blog_id:(NSString*)blog_id pull_direction:(NSString *)pull_dirction
{
__block NSMutableArray *dataToBeShown =[[NSMutableArray alloc] init];
__block NSMutableDictionary *resultsDictionary;
NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:title, #"title",category_id,#"category_id",limits,#"limits",blog_id,#"blog_id", pull_dirction,#"pull_direction",nil];
if ([NSJSONSerialization isValidJSONObject:userDictionary])
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];
NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
NSURL *url = [NSURL URLWithString:[[PropertyPlist getValue:#"RootURL"] stringByAppendingString:#"/rest/blog/search"]];
ASIHTTPRequest *_request = [ASIHTTPRequest requestWithURL:url];
__weak ASIHTTPRequest* request = _request;
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request setRequestMethod:#"POST"];
[request setPostBody:tempJsonData];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response = [request responseString];
NSLog(#"Test:%#",response);
NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];
FOOTPRINT;
resultsDictionary = [jsonData objectFromJSONData];
NSArray *dataArray = [resultsDictionary objectForKey:#"data"];
NSLog(#"即将进入FOR循环");
int i =0;
for ( NSDictionary *dict in dataArray){
NSMutableArray *tempArray =[[NSMutableArray alloc] init];
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"id"]];//取出ID
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"thumb"]];//取出缩略图地址
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"title"]];//取出title
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"auto_id"]];//取出auto_id
[dataToBeShown addObject:tempArray];
tempArray=nil;
i++;
}
NSLog(#"跳出FOR循环");
}];
[request setFailedBlock:^{
NSError *error1 = [request error];
NSLog(#"ERROR IS %#",error1);
}];
[request startAsynchronous];
[ASIHTTPRequest setDefaultUserAgentString:kUserAgentString];
}
return dataToBeShown;
METHOD_END;
}
in cellForRowAtIndexPath
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *indentifier=#"indentifier";
RecommedTableViewCell *cell =(RecommedTableViewCell *)[tableView dequeueReusableCellWithIdentifier:indentifier];
if (cell == NULL)
{
cell=[[RecommedTableViewCell alloc]init]; }
NSInteger row=[indexPath row];
cell.titleLabel.text =[[dataToBeShown objectAtIndex:row] objectAtIndex:2];
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
return cell;
}
It will crash as soon as the app is started for EXC_BAD_ACCESS.When I commit out
cell.titleLabel.text =[[dataToBeShown objectAtIndex:row] objectAtIndex:2];
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
,not crash.So I found the dataToBeShown is null.How can I do it?
Please check the array before assigning
if(row
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
}
or do the checking in numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return dataToBeShown.count;
}
This will remove the EXC_BAD_ACCESS.
I had a uipickerview in my detailed page. I want to get the value selected by default when I edit the respective record which comes from my tableviewcell. In short I had a tableview with 10 records. When I select a record from tableview cell it navigates to detailed page which contains three picker views with one component each. I want the picker view to load the selected value by default. Here is the below code how Iam loading the data. How can I display the selected value in -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row and one more thing is I am using UINavigationcontroller for this page? Guys Can u please help me out
-(void)loadprojects
{
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://xxx.xxx/GetAssignedProjects";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,usrid];
NSURL *url = [NSURL URLWithString:projecturl];
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) {
projID = [entries valueForKey:#"ID_PROJECT"];
projectNames = [entries valueForKey:#"NM_PROJECT"];
}
randomSelection=[BenefitNames arrayByAddingObjectsFromArray:projectNames];
randomSelectionID = [benID arrayByAddingObjectsFromArray:projID];
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}
-(void)loaddata
{
NSString *eventDate = self.projidstocancel;
[[NSUserDefaults standardUserDefaults] setObject:eventDate forKey:#"Eventdate"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *post =[[NSString alloc] initWithFormat:#"username : %#&Password :%#",[self.projectpicker dataSource],[self.projectpicker delegate]];
//NSString *pickername = [self.projectpicker dataSource];
//NSString *key = #"Da9s^a2Rp4na6R$ikiAsav3Is#niWsa";
//NSString *encrypteduname = [AESCrypt encrypt:pickername password:key];
// Code for Project loading
NSString *projecturltemp = #"http://xxx.xxxx/GetDetailsByID";
NSString *str = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserLoginIdSession"];
NSString *usrid = str;
NSString * projecturl =[NSString stringWithFormat:#"%#/%#",projecturltemp,self.hdnRowcount];
NSURL *url = [NSURL URLWithString:projecturl];
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"];
hdnlblProjects.text = [[entries valueForKey:#"NM_PROJECT"]componentsJoinedByString:#""];
hdnlblTasks.text = [[entries valueForKey:#"TASk_NAME"]componentsJoinedByString:#""];
hdnlblSubTasks.text = [[entries valueForKey:#"SUBTASK_NAME"]componentsJoinedByString:#""];
txthours.text = [[entries valueForKey:#"No_Hours"]componentsJoinedByString:#""];
txtstatus.text = [[entries valueForKey:#"STATUS"]componentsJoinedByString:#""];
lblBenefitsLeaves.text = [[entries valueForKey:#"NM_LEAVE"]componentsJoinedByString:#""];
BenefitNames = [entries valueForKey:#"NM_LEAVE"];
projID = [entries valueForKey:#"ID_PROJECT"];
taskID = [entries valueForKey:#"ID_TASK"];
subtskID = [entries valueForKey:#"ID_SUB_TASK"];
}
lblProjects.text = [[projID valueForKey:#"description"] componentsJoinedByString:#""];
taskstring = [[taskID valueForKey:#"description"] componentsJoinedByString:#""];
subtaskstring = [[subtskID valueForKey:#"description"] componentsJoinedByString:#""];
bentest = [[BenefitNames valueForKey:#"description"] componentsJoinedByString:#""];
hrsdiff1 = [txthours.text floatValue];
}
} else {
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
int numberofRows = 0;
if([pickerView isEqual: _projectpicker]){
numberofRows = [randomSelection count];
return numberofRows;
}
else if([pickerView isEqual: _taskspicker]){
numberofRows = [taskNames count];
return numberofRows;
}
else if([pickerView isEqual: _subtaskspicker]){
numberofRows = [subtaskNames count];
return numberofRows;
}
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *title = #"Test";
if([pickerView isEqual: _projectpicker]){
title = [randomSelection objectAtIndex:row];
return title;
}
else if ([pickerView isEqual: _taskspicker]){
title = [taskNames objectAtIndex:row];
return title;
}
else if ([pickerView isEqual: _subtaskspicker]){
title = [subtaskNames objectAtIndex:row];
return title;
}
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//NSLog(#"%#",myArrayString);
//NSLog(#"%#",myTaskArrayString);
if([pickerView isEqual: _projectpicker]){
NSNumber *myProjectArrayString = [randomSelectionID objectAtIndex:row];
lblProjects.text = [NSString stringWithFormat:#"%#",myProjectArrayString];
lblProjects.hidden = YES;
lblBenefitsLeaves.text = [randomSelection objectAtIndex:row];
hdnlblProjects.text = [randomSelection objectAtIndex:row];
rownoedit = row;
lblTasks.text = #"0";
hdnlblTasks.text = #"--Select--";
lblSubTasks.text = #"0";
hdnlblSubTasks.text = #"--Select--";
[self loadtasks];
}
//lblProjects.hidden = YES;
else if([pickerView isEqual: _taskspicker])
{
NSNumber *myTaskArrayString = [taskID objectAtIndex:row];
lblTasks.text = [NSString stringWithFormat:#"%#",myTaskArrayString];
lblTasks.hidden = YES;
hdnlblTasks.text = [taskNames objectAtIndex:row];
lblSubTasks.text = #"0";
hdnlblSubTasks.text = #"--Select--";
[self loadsubtasks];
}
else if([pickerView isEqual: _subtaskspicker])
{
NSNumber *mysubtaskArrayString = [subtskID objectAtIndex:row];
lblSubTasks.text = [NSString stringWithFormat:#"%#",mysubtaskArrayString];
lblSubTasks.hidden = YES;
hdnlblSubTasks.text = [subtaskNames objectAtIndex:row];
//lblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
//lblTasks.text = [NSString stringWithFormat:#"%#", myTaskArrayString];
//lblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
}
}
First define a static variable and give it initial value you like to first on load
ex : static int selectedRow = 3
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
selectedRow = [pickerView selectedRowInComponent:0];
}
and then where you show pickerView place this line
[self selectRow:selectedRow inComponent:0 animated:YES];
Try with following code
[self.yourPickerViewName selectRow:self.valueName inComponent:0 animated:YES];
Where
self.valueName is value that select record from tableview cell. and Put above code after creation of your UIPickerView.
You can refer this to fetch selected value from pickerview
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if([pickerView isEqual:StatePicker])
{
stateName = [StateArray objectAtIndex:row]; //StateName is NSString, StateArray is Array
}
}