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];
}
Related
I need to display particular object for key(currency) using post method after getting response from web.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController{
NSMutableData *mutableData;
NSMutableString *arr;
#define URL #"website"
// change this URL
#define NO_CONNECTION #"No Connection"
#define NO_VALUES #"Please enter parameter values"
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)sendDataUsingPost:(id)sender{
[self sendDataToServer :#"POST"];
}
-(IBAction)sendDataUsingGet:(id)sender{
[self sendDataToServer : #"GET"];
}
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid=#"3";
serverResponse.text = #"Getting response from server...";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
NSLog(#"responseData: %#", arr);
//NSLog(#"%#",[[arr valueForKey:#"BranchByList"]objectForKey:#"currency"]);
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
if( connection )
{
mutableData = [NSMutableData new];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
serverResponse.text = NO_CONNECTION;
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableString *responseStringWithEncoded = [[NSMutableString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
//NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSLog(#"%#",responseStringWithEncoded );
NSLog(#"%#",[responseStringWithEncoded valueForKeyPath:#"BranchByList.currency"] );
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
// NSLog(#"%#",attrStr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
i got response branch_id=3 but i want to show to "currency" but i tried lot but failure.
my response like this I need to display only currency.....
Response from Server :
{"BranchByList":
[
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
},
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
}
]};
Your response structure is:
-Dictionary
--Array
---Dictionary Objects
You need to convert your Data into NSDictionary to parse it.
Following code will do that for you:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
NSArray* responseArray = [json objectForKey:#"BranchByList"]; //Now we got mid level response array
//Get Embeded objects from response Array:
NSDictionary *priceDic = [responseArray objectAtIndex:0]; //Getting first object since you arent telling what the second object is for
NSString *buyingPrice = [priceDic objectForKey: #"buy"]; //Buying price
NSString *sellingPrice = [priceDic objectForKey:#"sell"]; //Selling price
NSString *currency = [priceDic objectForKey:#"currency"]; //Currency
Though this is only sticking to the point and getting the job done.
Proper way to get the job done would be to create a model class for response. Create a class inherited from NSObject and use it as model for this response. Add a initWithDic: method to that class, Pass it your response dic as parameter and delegate all this dictionary parsing to that method.
Also, NSURLConnection is deprecated since iOS 9.0. You should use NSURLSession instead.
Try This May be it will help you:-
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMArray *array1 = [dict6 objectForKey:#"BranchByList"];
NSLog(#"DICT : %#",array1);
NSDictionary *Dict3 = [array1 objectAtIndex:0];
NSString *Str1 = [dict3 objectForKey:#"currency"];
NSLog(#"Str1 : %#",Str1);
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else
{
return jsonObject;
}
}
I am trying to integrate payu money payment gateway in my app.
Payumoney collect all information and done transaction and return back to my custom defined url webpage.
My problem is how to get the response code after successful transaction from payu money gateway?
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];
NSString *txnid1 = [strHash substringToIndex:20];
NSLog(#"tnx1 id %#",txnid1);
// NSString *key = #"JBZaLc";
// NSString* salt = #"GQs7yium";
NSString *key = #"gtKFFx";
NSString* salt = #"eCwWELxi";
NSString *amount = dataMoney.usrAmount;
NSString *productInfo = #"App Products Info ";
NSString *firstname = dataMoney.usrName;
NSString *email = dataMoney.usrEmail;
NSString *phone = dataMoney.usrMobile;
NSString *surl = #"https://dl.dropboxusercontent.com/s/dtnvwz5p4uymjvg/success.html";
NSString *furl = #"https://dl.dropboxusercontent.com/s/z69y7fupciqzr7x/furlWithParams.html";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,surl,furl,hash, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash", nil]];
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
}else{
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://test.payu.in/_payment"]]];
// change URL for live
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[web_view_PayU loadRequest:request];
#define Merchant_Key #"your merchant key "
#define Salt #"your salt key"
#define Base_URL #"https://secure.payu.in"
> //this base url in case of origional payment key's if you want to integarate with
test key's write base Url can check in payumoney Faq
**
#define Success_URL #"https://www.google.co.in/"
#define Failure_URL #"http://www.bing.com/"
#define Product_Info #"Denim Jeans"
#define Paid_Amount #"1549.00"
#define Payee_Name #"Suraj Mirajkar"
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self setTitle:#"Make A Payment"];
[self initPayment];
}
- (void)viewDidLoad {
[super viewDidLoad];
activityIndicatorView = [[UIActivityIndicatorView alloc] init];
activityIndicatorView.center = self.view.center;
[activityIndicatorView setColor:[UIColor blackColor]];
[self.view addSubview:activityIndicatorView];
}
-(void)initPayment {
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];// Generatehash512(rnd.ToString() + DateTime.Now);
NSString *txnid1 = [strHash substringToIndex:20];
strMIHPayID = txnid1;
NSString *key = Merchant_Key;
NSString *amount =[[NSUserDefaults standardUserDefaults]
stringForKey:#"orderprice"];
//NSString *amount = Paid_Amount;
NSString *productInfo = Product_Info;
NSString *firstname = Payee_Name;
NSString *email = [NSString stringWithFormat:#"suraj%d#yopmail.com",i];
//ADD A fake mail For Payment for testing purpose
// Generated a fake mail id for testing
NSString *phone = #"9762159571";
NSString *serviceprovider = #"payu_paisa";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,Salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,Success_URL,Failure_URL,hash,serviceprovider
, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash",#"service_provider", nil]];
NSLog(#"%#",parameters);
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
} else {
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/_payment",Base_URL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[_webviewPaymentPage loadRequest:request];
[activityIndicatorView startAnimating];
}
-(NSString *)createSHA512:(NSString *)string {
const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:string.length];
uint8_t digest[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) {
[output appendFormat:#"%02x", digest[i]];
}
return output;
}
#pragma UIWebView - Delegate Methods
-(void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"WebView started loading");
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[activityIndicatorView stopAnimating];
if (webView.isLoading) {
return;
}
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView finished loading with requestURL: %#",requestURL);
NSString *getStringFromUrl = [NSString stringWithFormat:#"%#",requestURL];
if ([self containsString:getStringFromUrl :Success_URL]) {
[self performSelector:#selector(delayedDidFinish:) withObject:getStringFromUrl afterDelay:0.0];
} else if ([self containsString:getStringFromUrl :Failure_URL]) {
// FAILURE ALERT
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Sorry !!!" message:#"Your transaction failed. Please try again!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[activityIndicatorView stopAnimating];
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView failed loading with requestURL: %# with error: %# & error code: %ld",requestURL, [error localizedDescription], (long)[error code]);
if (error.code == -1009 || error.code == -1003 || error.code == -1001) { //error.code == -999
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Oops !!!" message:#"Please check your internet connection!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
- (void)delayedDidFinish:(NSString *)getStringFromUrl {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Success" forKey:#"Transaction_Status"];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
});
}
#pragma UIAlertView - Delegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 1 && buttonIndex == 0) {
// Navigate to Payment Status Screen
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Failed" forKey:#"Transaction_Status"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
}
}
- (BOOL)containsString: (NSString *)string : (NSString*)substring {
return [string rangeOfString:substring].location != NSNotFound;
}
- (void)navigateToPaymentStatusScreen: (NSMutableDictionary *)mutDictTransactionDetails {
dispatch_async(dispatch_get_main_queue(), ^{
PaymentStatusViewController *paymentStatusViewController = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"PaymentStatusScreenID"];
paymentStatusViewController.mutDictTransactionDetails = mutDictTransactionDetails;
[self.navigationController pushViewController:paymentStatusViewController animated:YES];
});
}
Important Note : you can check your Merchant key and Salt in seller Dashboard after Login ... Go To my account and check your merchant key and salt
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...
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.