簡體   English   中英

如何在目標C中的日歷上從Web服務添加事件

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

我是iOS的新手,我在顯示日歷上的事件時遇到問題。我正在使用JTCalendar https://github.com/chu888chu888/IOS-JTCalendar

我的代碼是這樣的

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

它的輸出像是2017年2月6日在數組中。如何在日歷上顯示它。

在此處輸入圖片說明

它顯示了隨機事件。但是如何顯示日期事件呢?

提前致謝!

網絡服務

從3 Web服務獲得價值

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

您已經在源代碼中注釋了函數“ createRandomEvents”。

此功能定義要在日歷上顯示的日期。

從Web服務獲取事件數據,並且必須在數組“ eventsByDate”中添加日期。 然后,您應該可以查看日期。

代碼:-(void)viewDidLoad {[super viewDidLoad];

NSMutableArray *arrDates = [[NSMutableArray alloc] init];

}

在ScheduleKPI API響應中

[arrDates addObjectsFromArray:EndDatearrayScheduleKPI];

在ScheduleAudit API響應中

[arrDates addObjectsFromArray:EndDatearrayScheduleAudit];

在ScheduleMeeting API響應中

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM