Muju Muju - 2 months ago 7
iOS Question

How to add Events from web service on calendar in Objective C

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.

enter image description here

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);
}

Answer Source

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];
}