There are Three components (projects, tasks and sub tasks )in my pickerview when I select project, I was able to get the project name and respective project ID (Project ID is in label). My requirement is I want to send the project ID to NSURL so that I can load the respective tasks that are assigned to that project ID. Here is my Below Code.
ViewDidLoad:
// Code for Tasks loading
NSString *nsTaskurllocal = #"http://test.com/";
NSString *usrid = #"313";
NSString * productIdString =[NSString stringWithFormat:#"%#/%#",[self.lblProjects text],usrid];
NSLog(#"aString : %#", productIdString);
NSString *aString = [nsTaskurllocal stringByAppendingString:productIdString];
NSURL *nstaskurl = [NSURL URLWithString:aString];
NSLog(#"nstaskurl : %#", nstaskurl);
NSData *nstaskpostData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *nstaskpostLength = [NSString stringWithFormat:#"%lu", (unsigned long)[nstaskpostData length]];
NSMutableURLRequest *nstaskrequest = [[NSMutableURLRequest alloc] init];
[nstaskrequest setURL:nstaskurl];
[nstaskrequest setHTTPMethod:#"POST"];
[nstaskrequest setValue:nstaskpostLength forHTTPHeaderField:#"Content-Length"];
[nstaskrequest setValue:#"application/projectpicker" forHTTPHeaderField:#"Accept"];
[nstaskrequest setValue:#"application/jsonArray" forHTTPHeaderField:#"Content-Type"];
[nstaskrequest setHTTPBody:nstaskpostData];
NSError *nstaskerror = [[NSError alloc] init];
NSHTTPURLResponse *nstaskresponse = nil;
NSData *nstaskurlData=[NSURLConnection sendSynchronousRequest:nstaskrequest returningResponse:&nstaskresponse error:&nstaskerror];
NSURLRequest *nstaskurlRequest = [NSURLRequest requestWithURL:nstaskurl
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
nstaskurlData = [NSURLConnection sendSynchronousRequest:nstaskurlRequest
returningResponse:&nstaskresponse
error:&nstaskerror];
if ([nstaskresponse statusCode] >= 200 && [nstaskresponse statusCode] < 300)
{
NSString *nstaskresponseData = [NSJSONSerialization JSONObjectWithData:nstaskurlData
options:NSJSONReadingAllowFragments error:&nstaskerror];
NSArray *nstaskentries = [NSJSONSerialization JSONObjectWithData:[nstaskresponseData dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&nstaskerror];
if(!nstaskentries)
{
NSLog(#"Error : %#", nstaskerror);
}
else{
for (NSDictionary *nstaskentry in nstaskentries) {
taskID = [nstaskentries valueForKey:#"ID_TASK"];
taskNames = [nstaskentries valueForKey:#"TASk_NAME"];
//NSLog(#"Error : %#", taskNames); //log to see the result in console // by Kiran
}
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSNumber *myProjectArrayString = [projID objectAtIndex:row];
//NSNumber *myTaskArrayString = [taskID objectAtIndex:row];
//NSLog(#"%#",myArrayString);
//NSLog(#"%#",myTaskArrayString);
lblProjects.text = [NSString stringWithFormat:#"%#",myProjectArrayString];
//lblProjects.hidden = YES;
lblTasks.text = [taskNames objectAtIndex:[pickerView selectedRowInComponent:1]];
//lblTasks.text = [NSString stringWithFormat:#"%#", myTaskArrayString];
lblSubTasks.text = [subtaskNames objectAtIndex:[pickerView selectedRowInComponent:2]];
}
Thanks in Advance
Kiran Kumar
You need to differentiate between your total data, and your displayed data.
So, download all of your data and save it in projectNames, taskNames and subtaskNames. But also have 2 other properties: currentTaskNames and currentSubtaskNames (you don't need
cProjectNames because the user can always see all project names.
After the download:
self.currentTaskNames = taskNames;
self.currentSubtaskNames = subtaskNames;
Now, when the user selects a project, filter the tasks and subtasks that are available.
switch (component) {
case 0:
{
NSString *project = [projectNames objectAtIndex:row];
self.currentTaskNames = [taskNames filteredArrayUsingPredicate:...];
break;
}
case 1:
{
NSString *task = [taskNames objectAtIndex:row];
self.currentSubtaskNames = [subtaskNames filteredArrayUsingPredicate:...];
break;
}
case 2:
// do something interesting
break;
}
You need to fill in the predicates which filter out the tasks and subtasks that aren't appropriate based on the selected project and task.
Also, stop using labels for data storage...
Related
I am new in iOS and I am facing problem regarding to show events on calendar.I am using JTCalendar
https://github.com/chu888chu888/IOS-JTCalendar
My code is like this
In viewDidLoad
_calendarManager = [JTCalendarManager new];
_calendarManager.delegate = self;
// Generate random events sort by date using a dateformatter for the demonstration
//[self createRandomEvents];
// Create a min and max date for limit the calendar, optional
[self createMinAndMaxDate];
[_calendarManager setMenuView:_calendarMenuView];
[_calendarManager setContentView:_calendarContentView];
[_calendarManager setDate:_todayDate];
#pragma mark - CalendarManager delegate
// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (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]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor redColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Other month
else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
// Another day of the current month
else{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
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;
// Animation for the circleView
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];
// Don't change page in week mode because block the selection of days in first and last weeks of the month
if(_calendarManager.settings.weekModeEnabled){
return;
}
// Load the previous or next page if touch a day from another month
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];
// Min date will be 2 month before today
_minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-12];
// Max date will be 2 month after today
_maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:12];
}
// Used only to have a key for _eventsByDate
- (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)createRandomEvents
//{
// _eventsByDate = [NSMutableDictionary new];
//
// for(int i = 0; i < 30; ++i){
// // Generate 30 random dates between now and 60 days later
// NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
//
// // Use the date as key for eventsByDate
// NSString *key = [[self dateFormatter] stringFromDate:randomDate];
//
// if(!_eventsByDate[key]){
// _eventsByDate[key] = [NSMutableArray new];
// }
//
// [_eventsByDate[key] addObject:randomDate];
// }
//}
Its output is like this 02/06/2017 in array.How can I show it on calendar.
It is showing random events.But how can I show events on date?
Thanks in Advance!
Web Service
Getting value from 3 web service
#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>"
"<Get_Audits_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Audits_Schedules_User>"
"</soap:Body>"
"</soap:Envelope>",Auditid];
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/Get_Audits_Schedules_User" 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)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>"
"<Get_Kpi_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Kpi_Schedules_User>"
"</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/Get_Kpi_Schedules_User" 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)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>"
"<Get_Meeting_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Meeting_Schedules_User>"
"</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/Get_Meeting_Schedules_User" 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];
}
}
#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if(connection == myNSUConnectionObjScheduleAudit)
{
[myNSMDataFromServerScheduleAudit setLength:0];
}
if(connection == myNSUConnectionObjScheduleKPI)
{
[myNSMDataFromServerScheduleKPI setLength:0];
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
[myNSMDataFromServerScheduleMeeting setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if(connection == myNSUConnectionObjScheduleAudit)
{
[myNSMDataFromServerScheduleAudit appendData:data];
}
if(connection == myNSUConnectionObjScheduleKPI)
{
[myNSMDataFromServerScheduleKPI appendData:data];
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
[myNSMDataFromServerScheduleMeeting appendData:data];
}
}
- (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];
EndDatearrayScheduleAudit =[[NSMutableArray alloc] init];
EndDatearrayScheduleAudit=[responsedictScheduleAudit valueForKey:#"EndDate"];
}
}
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];
EndDatearrayScheduleKPI =[[NSMutableArray alloc] init];
EndDatearrayScheduleKPI =[responsedictScheduleKPI valueForKey:#"EndDate"];
}
}
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];
EndDatearrayScheduleMeeting =[[NSMutableArray alloc] init];
EndDatearrayScheduleMeeting =[responsedictScheduleMeeting valueForKey:#"EndDate"];
}
}
[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);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(#"DataArray: %#",myDataNSMArrayScheduleAudit);
}
You have commented function "createRandomEvents" in your source code.
This function defines your dates to be displayed on calendar.
Get events data from web service and you have to add dates in array "eventsByDate". Then you should be able to view dates.
Code:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *arrDates = [[NSMutableArray alloc] init];
}
In ScheduleKPI API response
[arrDates addObjectsFromArray:EndDatearrayScheduleKPI];
In ScheduleAudit API response
[arrDates addObjectsFromArray:EndDatearrayScheduleAudit];
In ScheduleMeeting API response
[arrDates addObjectsFromArray:EndDatearrayScheduleMeeting];
[self funAddEvents:arrDates];
- (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];
}
[self.calendar reloadData];
}
I had very minute problem since yesterday. I had 2 tables in the database one with Projects and other with Benefits. I want to add the two tables data in Single PickerView Component. For example Projects has pro1, proj2, proj3 and Benefits table has benefits1, benefits2. So I want to append both projects table dat and Benefits table data in a single PickerView component.
-(void)loadprojects
{
NSString *post =[[NSString alloc] initWithFormat:#"username=%#",[self.projectpicker dataSource]];
// Code for Project loading
NSString * BenefitString =#"http://test.com/GetBenefitTypes";
NSURL *Benefiturl = [NSURL URLWithString:BenefitString];
NSString *projecturltemp = #"http://test.com/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:Benefiturl];
[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];
NSURLRequest *urlRequestBenifits = [NSURLRequest requestWithURL:Benefiturl
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
urlData = [NSURLConnection sendSynchronousRequest:urlRequestBenifits
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"];
BenefitsNames = [entries valueForKey:#"NM_LEAVES"];
}
//Combined = [BenefitsNames arrayByAddingObjectsFromArray:projectNames];
NSLog(#"Combined : %#", projectNames);
//NSLog(#"projID : %#", projID);
_projectpicker.delegate = self;
_projectpicker.dataSource = self;
}
} else {
}
}
Are projects and benefits NSArray instances? If so why not just combine them into one array and use that moving forward?
NSArray *projects = #[#"pro 1", #"pro 2"];
NSArray *benefits = #[#"benefit 1", #"benefit 2"];
NSArray *combined = [projects arrayByAddingObjectsFromArray:benefits];
NSLog(#"Combined: %#", combined);
Combined prints out:
Combined: (
"pro 1",
"pro 2",
"benefit 1",
"benefit 2" )
Then in your - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component method just return the [combined objectAtIndex:row];
base on my understanding, you wanna have something like above? am i correct? so multiple component in a UIPickerView?
if so, 1st thing, you need to set delegations to your ViewController ->
<UIPickerViewDataSource, UIPickerViewDelegate>
then you implement the following methods in your ViewController.m file:
(I assume you have "NSArray *data" for projects and benefits ready...)
//Number of rows to display in each component
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component==0) {
return [self.listOfProjectsOfLeftCol count];
}
return [self.listOfBenefitsOfRightCol count];
}
//Number of columns to display
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
//define what to display in each rows and columns
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component==0) {
return [self.listOfProjectsLeftCol objectAtIndex:row];
}
return [self.listOfBenefitsOfRightCol objectAtIndex:row];
}
//when the row is selected , do something...
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component==0) {
//selected items in left column, now write your own code to do something...
}
else {
//selected items in right column, now write your own code to do something...
}
}
Not clear what do you mean by the combine the two component into one.
But I guess you want combination of project and benefit as Project:Benefit
If so u can use following code snippet
NSArray *arrProject=[NSArray arrayWithObjects:#"Project1",#"Project2",nil];
NSArray *arrBenefits=[NSArray arrayWithObjects:#"Benefits1",#"Benefits2",nil];
NSMutableArray *arrCombined=[[NSMutableArray alloc]init];
for(int i=0;i<[arrProject count];i++)
{
[arrCombined addObject:[NSString stringWithFormat:#"%#:%#",[arrProject objectAtIndex:i],[arrBenefits objectAtIndex:i]]];
}
NSLog(#"Combined:%#",arrCombined);
Its gives you result as
Combined:(
"Project1:Benefits1",
"Project2:Benefits2"
)
And then use the arrCombined for the date picker data source
I know that there are plenty of questions that have been asked and answered and non of them pertain to my problem.
I am posting XML to a server and I get a response back. My problem is getting a specified key back from the response.
I am trying to list all Genders e.g Male, Female and their id's however when parsing the XML into text with NSXML I only get back the Female and ID 2 and I do not get back Male?
I have researched and tried to fix this issue but to no avail.
here is my code:
- (void)getGender {
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<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/\" xmlns:app=\"http://app.ws.api.bells.wigroup.com/\">"
"<soap:Header/>\n"
"<soap:Body>\n"
"<app:getAllGenders>\n"
"<request>\n"
"<apiCredentials>\n"
"<apiId>IPHONE_APP</apiId>\n"
"<sha1Password>8656cafcd71cbbfe773a0fdb6c422666a80e5b8f</sha1Password>\n"
"</apiCredentials>\n"
"<request>\n"
"</request>\n"
"</request>\n"
"</app:getAllGenders>\n"
"</soap:Body>\n"
"</soap:Envelope>\n"
];
NSLog(#"Message%#",soapMessage);
NSURL *url = [NSURL URLWithString:#"http://qa.wigroup.co:8080/bells/AppWS"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//[theRequest addValue: #"http://" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response XML:%#",str);
// create and init NSXMLParser object
XmlArrayParser *parser = [[XmlArrayParser alloc] initWithData:urlData];
parser.rowElementName = #"return";
parser.elementNames = [NSArray arrayWithObjects:#"response", #"responseCode", #"responseDesc", #"gendersList", nil];
parser.attributeNames = [NSArray arrayWithObjects:#"id", #"gender", nil];
if ([parser.rowElementName isEqualToString:#"responseCode"] && _flag)
{
//read the value here
NSLog(#"flagging");
}
// parsing...
BOOL success = [parser parse];
// test the result
if (success)
{
NSMutableArray *loginAuth = [parser items];
// self.textView.text = [NSString stringWithFormat:
// #"This is an array of dictionaries, one dictionary for each user:\n\n%#",
// [users description]];
// NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:#"response", nil];
NSDictionary *loginResponse = [loginAuth objectAtIndex:0]; // this retrieves the first user
NSString *userResponse = loginResponse[#"gendersList"]; // this retrieves that user's username in Xcode 4.5 and greater
NSString *userRes = [loginResponse objectForKey:#"id"];
NSString *test = [loginAuth description];
NSLog(#"Returned Code loginResponse %#",loginResponse);
NSLog(#"Returned Code userResponse %# %#",userResponse, userRes);
NSLog(#"Returned Code test %#",test);
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:10];
for (NSDictionary *defineXMLData in loginAuth) {
NSNumber * responseCode = [defineXMLData objectForKey:#"responseCode"];
NSArray * responseDEsc = [defineXMLData objectForKey:#"responseDesc"];
NSArray * genderList = [defineXMLData objectForKey:#"gendersList"];
// NSArray * gender = [defineJsonData objectForKey:#"gender"];
NSLog(#"Genders%#", genderList);
[array addObject: responseCode];
[array addObject: responseDEsc];
[array addObject: genderList];
//[array addObject: gender];
// [array addObject: vouchersUser];
}
label.numberOfLines = 2000; // for example
label.lineBreakMode = NSLineBreakByClipping;
NSString *output=[array componentsJoinedByString:#","];
label.text = [NSString stringWithFormat:#"XML Result: %# ",output];
[SVProgressHUD dismiss];
// [[[UIAlertView alloc] initWithTitle:nil
// message:[NSString stringWithFormat:#"No errors - user count : %i", [[parser items] count]]
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil] show];
}
else
{
NSLog(#"Error parsing document!");
// [[[UIAlertView alloc] initWithTitle:nil
// message:#"Error parsing document!"
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil] show];
}
}
else
{
NSLog(#"theConnection is NULL");
}
NSLog(#"test");
}
And the XML I get back from my nslog:
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getAllGendersResponse xmlns:ns2="http://app.ws.api.bells.wigroup.com/">
<return>
<responseCode>-1</responseCode>
<responseDesc>Success</responseDesc>
<response>
<responseCode>-1</responseCode>
<responseDesc>Success</responseDesc>
<gendersList>
<gender>Male</gender>
<id>1</id>
</gendersList>
<gendersList>
<gender>Female</gender>
<id>2</id>
</gendersList>
</response>
Is only parsing:
{
gendersList = Female2;
responseCode = "-1";
responseDesc = Success;
}
You have not correctly pointed the problem. Your code parses the whole document, but you keep only the last items (last genderList, last responseCode, last responseDesc). Initialize an array and in your for loop add each dictionary to that array when parsed.
I get four parameters from a web service (web service 2 in my flow) - slno, order, flag, name. I don't know how many times these parameters are going to be received. Out of these four paramters, I send 'name' to a label as it contains questions to be asked.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"some url"]];
NSLog(#"Web service 2 url is = %#", url);
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"Json data = %# \n error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:Nil];
//NSArray *arrayLabel = [[NSArray alloc] initWithObjects:label1, label2, label3, label4, label5, label6, nil];
//NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:myJsonArray.count];
i = 0;
for(NSDictionary *myJsonDictionary in myJsonArray)
{
//UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
//[label setText:myJsonDictionary[#"Name"]];
NSString *name = myJsonDictionary[#"Name"];
NSLog(#"Question from ws2 is %#", name);
projectIdGobal = myJsonDictionary[#"ProjectID"];
NSLog(#"Project id from ws2 is %#", projectIdGobal);
slno = myJsonDictionary[#"SLNO"];
NSLog(#"slno from ws2 is %#", slno);
NSString *idWS2 = myJsonDictionary[#"ID"];
NSLog(#"id from ws2 is %#", idWS2);
order = myJsonDictionary[#"Order"];
NSLog(#"order from ws2 is %#", order);
flag = myJsonDictionary[#"Flag"];
NSLog(#"flag from ws2 is %#", flag);
[self putLabelsInScrollView:name];
i++;
}
NSLog(#"Number of cycles in for-each = %d", i);
[activity stopAnimating];
}
- (void) putLabelsInScrollView:(NSString *)labelText
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
[label setText:labelText];
[self.scroll addSubview:label];
yPosition_label += 90;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 90;
yPosition_result = yPosition_label + yPosition_text;
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
}
Now I created a dynamically created text fields and stored the answers entered by the user in the array as follows.
- (IBAction)save:(id)sender {
NSMutableArray *mutableTextArray = [[NSMutableArray alloc] init];
for(UITextField *field in self.scroll.subviews)
{
if([field isKindOfClass:[UITextField class]])
{
if([[field text] length] > 0)
{
[mutableTextArray addObject:field.text];
//NSLog(#"Save button 1 : %#", mutableTextArray);
//NSString *str = [str stringByAppendingString:[mutableTextArray objectAtIndex:0]];
//[self fetchStrings:mutableTextArray];
}
}
}
NSLog(#"Save button 2 : %#", mutableTextArray);
[self fetchStrings:mutableTextArray];
}
Now while posting the answer to another web service (web service 3 in my flow), I must pass slno, order, flag i get from web service 2 and the 'answer' that the user enters in the dynamically created field to the 'answer' key. How shall I get these 4 parameters [slno, order, flag (from web service 2) and answer (from dynamic text field)] to post to web service 3?
- (void) fetchStrings:(NSArray *)textArray
{
NSLog(#"Array string = %#", textArray); //I get the array that the user enters in the dynamically created text field here
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSUserDefaults *getDefaults = [NSUserDefaults standardUserDefaults];
NSString *uidObject = [getDefaults objectForKey:#"UIDKEY"];
NSString *str = [NSString stringWithFormat:#"{\"ProjID\": \"%#\",\"Uid\": \"%#\",\"EmailID\": \"%#\",", projectIdGobal, uidObject, emailFromLogin];
str = [str stringByAppendingString:#"\"ProjectInviterFQAnswers\": ["];
**for (SaveAsking *saveAsk in textArray) {
str = [str stringByAppendingString:[NSString stringWithFormat:#"{\"slno\":\"%#\",\"Answer\": \"%#\",\"order\": \"%#\", \"flag\": \"%#\"},", saveAsk.slno, saveAsk.answer, saveAsk.order, saveAsk.flag]]; // I want to save the parameters here
}**
// SaveAsking is a nsobject class where I have used a self created delegate for slno answer order and flag
str = [str stringByAppendingString:#"]}"];
NSLog(#"String is === %#", str);
NSURL *url = [NSURL URLWithString:#"some url"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if(error || !data)
{
NSLog(#"JSON Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Data not saved" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(#"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Response is %#", jsonObject);
}
}];
}
Please do correct my flow if you understood what am i trying to achieve. Number for iterations in left box == number of iterations in right box and the result is in the middle box which needs to be posted to web service.
Try keeping a dictionary of the requests, where the key would be the dynamically created UITextField, and the value would be another dictionary with the values that you need to send.
So , when you create the textField, after adding it to the subview, create a dictionary with your values (sino, order, flag), and set that dictionary to the textfield.
When you are ready to send the data, you'll have a direct connection between the textField and the values for your webservice3.
I'm making an app that requires you to login in. I"m using JSON. So far I've been able send a POST request with the Username and Password and I get a token back (it shows up in the console). When I don't enter in the correct username/password combination, I don't get a token back. What I would like to happen is to proceed to the next view controller if I get a token back. I think that I need to use an if statement (I'll put the code for switching view controllers into it) but I don't know what parameters I need in order to check if I get a token back.
Here is the code I'm using in the implementation file. It is in a method that runs when a button is pressed:
#try {
if([[usernameTextField text] isEqualToString:#""] || [[passTextField text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[usernameTextField text],[passTextField text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://beta.network360.com/tokens"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [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];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%d",success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#""];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#""];
}
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#""];
//[[PSearchViewController new] performSegueWithIdentifier:#"loginCancel" sender:self];
}
Also, here is what I get in the console output when I put in the correct username/password combination (BTW I tried to change all the stuff that showed up in the console that was confidential, so if some stuff doesn't quite match, it should be fine. I just wanted to show that I get a token back):
2013-07-28 13:23:21.607 Empyrean[28283:c07] PostData: username=username#gmail.com&password=password
2013-07-28 13:23:22.300 Empyrean[28283:c07] Response code: 200
2013-07-28 13:23:22.301 Empyrean[28283:c07] Response ==> {"token":"scFDzxSAVk2sxQBShEGS","user":{"id":300230,"username":"username#gmail.com","display_name":"FirstName LastName","unconfirmed_email":null,"email":"username#gmail.com","confirmation_email":"username#gmail.com","client_identifier":null,"client_id":138,"is_admin":false,"support_email":"support#supportemail.com","application_name":"AppName","show_project_vintage_date":false,"is_anonymous":false,"is_active":true,"is_confirmed":true,"pending_reconfirmation":false,"can_resend_confirmation":false,"client_name":"Broker","show_advertisements":true,"header_logo":"/foo/headerlogo.gif","report_footer_logo":"/stuff/foo/footerlogo.png","authorized_features":["find_stuff","do_stuff","stuff_stuff","settings","menu","manage_stuff","measure_stuff","export_stuff"],"url":"https://www.website.com/stuff/numbersdsjkflds"}}
2013-07-28 13:23:22.304 Empyrean[28283:c07] {
token = dlsfkasdfDfdsklfdDsa;
user = {
"application_name" = "Application Name";
"authorized_features" = (
"find_stuff",
"do_stuff",
"stuff_stuff",
settings,
menu,
"manage_stuff",
"measure_stuff",
"export_stuff"
);
"can_resend_confirmation" = 0;
"client_id" = 138;
"client_identifier" = "<null>";
"client_name" = Broker;
"confirmation_email" = "username#gmail.com";
"display_name" = "FirstName LastName";
email = "username#gmail.com";
"url" = "https://www.website.com/stuff/numbersdsjkflds";
"header_logo" = "/foo/headerlogo.gif";
id = 300230;
"is_active" = 1;
"is_admin" = 0;
"is_anonymous" = 0;
"is_confirmed" = 1;
"pending_reconfirmation" = 0;
"report_footer_logo" = "/stuff/foo/footerlogo.png";
"show_advertisements" = 1;
"show_project_vintage_date" = 0;
"support_email" = "support#supportemail.com";
"unconfirmed_email" = "<null>";
username = "username#gmail.com";
};
}
NSDictionary *jsonData is a dictionary. Therefore, you can see if the token key exists.
if (jsonData[#"token"])
{
// Token exists, so move on.
[self.navigationController pushViewController:nextController animated:YES];
}
else
{
// Tell the user they messed it up.
}