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
}
}
Related
I am new in iOS and I am facing problem regarding to show multiple events on same date.I am using JTCalendar.
My code is like this
In ViewDidLoad
_calendarManager = [JTCalendarManager new];
_calendarManager.delegate = self;
[self createMinAndMaxDate];
[_calendarManager setMenuView:_calendarMenuView];
[_calendarManager setContentView:_calendarContentView];
[_calendarManager setDate:_todayDate];
In viewWillAppear I code to change colour according to web service
[self serverconnectionScheduleAudit];
[self serverconnectionScheduleKPI];
[self serverconnectionScheduleMeeting];
#pragma mark - CalendarManager delegate
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
// Today
if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor blueColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Selected date
else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
if([CheckString isEqualToString:#"0"])
{
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor redColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
else if ([CheckString isEqualToString:#"1"])
{
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor orangeColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
else if ([CheckString isEqualToString:#"2"])
{
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor greenColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
}
// Other month
else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
if([CheckString isEqualToString:#"0"])
{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
else if ([CheckString isEqualToString:#"1"])
{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor orangeColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
else if ([CheckString isEqualToString:#"2"])
{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor greenColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
}
// Another day of the current month
else{
if([CheckString isEqualToString:#"0"])
{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor blackColor];
}
else if ([CheckString isEqualToString:#"1"])
{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor orangeColor];
dayView.textLabel.textColor = [UIColor blackColor];
}
else if ([CheckString isEqualToString:#"2"])
{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor greenColor];
dayView.textLabel.textColor = [UIColor blackColor];
}
}
if([self haveEventForDay:dayView.date]){
dayView.dotView.hidden = NO;
}
else{
dayView.dotView.hidden = YES;
}
}
- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
_dateSelected = dayView.date;
dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
[UIView transitionWithView:dayView
duration:.3
options:0
animations:^{
dayView.circleView.transform = CGAffineTransformIdentity;
[_calendarManager reload];
} completion:nil];
if(_calendarManager.settings.weekModeEnabled){
return;
}
if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
[_calendarContentView loadNextPageWithAnimation];
}
else{
[_calendarContentView loadPreviousPageWithAnimation];
}
}
}
#pragma mark - CalendarManager delegate - Page mangement
// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}
- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
// NSLog(#"Next page loaded");
}
- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
// NSLog(#"Previous page loaded");
}
#pragma mark - Fake data
- (void)createMinAndMaxDate
{
_todayDate = [NSDate date];
_minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-12];
_maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:12];
}
- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter;
if(!dateFormatter){
dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"dd-MM-yyyy";
}
return dateFormatter;
}
- (BOOL)haveEventForDay:(NSDate *)date
{
NSString *key = [[self dateFormatter] stringFromDate:date];
if(_eventsByDate[key] && [_eventsByDate[key] count] > 0){
return YES;
}
return NO;
}
-(void)funAddEvents:(NSArray *)arrDate
{
_eventsByDate = [NSMutableDictionary new];
for(NSString *strDate in arrDate){
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"YYYY/MM/dd"];
NSDate *myDate = [dateformat dateFromString:strDate];
NSString *key = [[self dateFormatter] stringFromDate:myDate];
if(!_eventsByDate[key]){
_eventsByDate[key] = [NSMutableArray new];
}
[_eventsByDate[key] addObject:myDate];
}
}
Connection Methods and Delegate
#pragma mark - Schedule Audit Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleAudit{
[customActivityIndicator startAnimating];
int Auditid =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<AuditMethod xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</AuditMethod>"
"</soap:Body>"
"</soap:Envelope>",Auditid];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/AuditMethod" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleAudit=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleAudit);
if(myNSUConnectionObjScheduleAudit)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleAudit=[[NSMutableData alloc]init];
}
}
#pragma mark - Schedule Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleKPI{
int KPI =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<KPIMethod xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</KPIMethod>"
"</soap:Body>"
"</soap:Envelope>",KPI];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/KPIMethod" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleKPI=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleKPI);
if(myNSUConnectionObjScheduleKPI)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleKPI=[[NSMutableData alloc]init];
}
}
#pragma mark - Schedule Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleMeeting{
int KPI =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<MeetingMethod xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</MeetingMethod>"
"</soap:Body>"
"</soap:Envelope>",KPI];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
// NSURLRequest *myNSURequestObj=[NSURLRequest requestWithURL:myNSUObj];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/MeetingMethod" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleMeeting=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleMeeting);
if(myNSUConnectionObjScheduleMeeting)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleMeeting=[[NSMutableData alloc]init];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if(connection == myNSUConnectionObjScheduleAudit)
{
loginStatusScheduleAudit = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleAudit mutableBytes] length:[myNSMDataFromServerScheduleAudit length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleAudit);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleAudit error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleAudit = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleAudit);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Audits_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Audits_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleAudit = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
ScheduleDatearrayScheduleAudit=[[NSMutableArray alloc] init];
ScheduleDatearrayScheduleAudit =[responsedictScheduleAudit valueForKey:#"StartDate"];
CheckString=#"0";
[self funAddEvents:EndDatearrayScheduleAudit];
}
}
if(connection == myNSUConnectionObjScheduleKPI)
{
loginStatusScheduleKPI = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleKPI mutableBytes] length:[myNSMDataFromServerScheduleKPI length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleKPI);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleKPI error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleKPI = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleKPI);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Kpi_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Kpi_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleKPI = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
StartDatearrayScheduleKPI =[[NSMutableArray alloc] init];
StartDatearrayScheduleKPI =[responsedictScheduleKPI valueForKey:#"StartDate"];
CheckString=#"1";
[self funAddEvents:EndDatearrayScheduleKPI];
}
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
loginStatusScheduleMeeting = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleMeeting mutableBytes] length:[myNSMDataFromServerScheduleMeeting length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleMeeting);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleMeeting error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleMeeting = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleMeeting);
NSDictionary* AddressDict=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",AddressDict);
NSDictionary *new =[AddressDict objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Meeting_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Meeting_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleMeeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
StartDatearrayScheduleMeeting =[[NSMutableArray alloc] init];
StartDatearrayScheduleMeeting =[responsedictScheduleMeeting valueForKey:#"StartDate"];
CheckString=#"2";
[self funAddEvents:EndDatearrayScheduleMeeting];
}
}
NSMutableArray *arrDates=[[NSMutableArray alloc] init];
[arrDates addObjectsFromArray:StartDatearrayScheduleKPI];
[arrDates addObjectsFromArray:ScheduleDatearrayScheduleAudit];
[arrDates addObjectsFromArray:StartDatearrayScheduleMeeting];
[self funAddEvents:arrDates];
[customActivityIndicator stopAnimating];
}
#pragma mark - NSXMLParsing Delegate
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"FillBlocksNew"])
{
myDataClassObjScheduleAudit=[[mydata alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
myMutableStringObjScheduleAudit=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleAudit);
NSData *dataAudit = [myMutableStringObjScheduleAudit dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleAudit = [NSJSONSerialization JSONObjectWithData:dataAudit options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleAudit);
myMutableStringObjScheduleKPI=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleKPI);
NSData *dataKPI = [myMutableStringObjScheduleKPI dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleKPI = [NSJSONSerialization JSONObjectWithData:dataKPI options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleKPI);
myMutableStringObjScheduleMeeting=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleMeeting);
NSData *dataMeeting = [myMutableStringObjScheduleMeeting dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleMeeting = [NSJSONSerialization JSONObjectWithData:dataMeeting options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleMeeting);
}
This is how I am showing
I need to show multiple events like this in the image
I need to show 2,3 events on the same date on the JTCalendar form the web service and in the different colour.How to do this can anyone try like this.Thanks in Advance!
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 :)
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];
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;
}
}
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.