2013-03-25 1 views
1

공유 Google 캘린더 IOS에서 내 이벤트를 가져 와서 테이블 뷰에 표시하고 있습니다. 현재로서는 이벤트 제목을 제목으로, 이벤트 시간을 부제로 표시하는 것이 간단합니다. 예를 들어 3 월 31 일에 그룹의 "세부 사항"으로 표시된 시간과 함께 모든 이벤트가 섹션 헤더로 사용됩니다 () JSON 데이터를 IOS6 앱의 섹션과 함께 표시하고 싶습니다.

내 코드는 다음과 같습니다. this :

@interface MasterViewController() { 
    NSArray *events; 
} 
@end 

@implementation MasterViewController 

-(void)viewDidAppear:(BOOL)animated 
{ 
    //show loader view 
    //[HUD showUIBlockingIndicatorWithText:@"Fetching JSON"]; 


    //make HTTP call 
    NSString* searchCall = [NSString stringWithFormat:@"http://www.google.com/calendar/feeds/kao1d80fd2u5kh7268caop11o4%%40group.calendar.google.com/public/full?alt=json"]; 

    [JSONHTTPClient getJSONFromURLWithString: searchCall 
            completion:^(NSDictionary *json, JSONModelError *err) { 

             //got JSON back 
             NSLog(@"Got JSON from web: %@", json); 

             if (err) { 
              [[[UIAlertView alloc] initWithTitle:@"Error" 
                     message:[err localizedDescription] 
                    delegate:nil 
                  cancelButtonTitle:@"Close" 
                  otherButtonTitles: nil] show]; 
              return; 
             } 

             //initialize the models 
             events = [CalendarModel arrayOfModelsFromDictionaries: 
               json[@"feed"][@"entry"] 
               ]; 

             if (events) NSLog(@"Loaded successfully models"); 

             //show the videos 
             [self.tableView reloadData]; 

            }]; 


} 
; 

#pragma mark - table methods 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return events.count; 
} 

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    CalendarModel* event = events[indexPath.row]; 


    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSzzz"; 
    NSDate *gmtDate = [formatter dateFromString: [[event.time objectAtIndex:0] startTime]]; 


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
    cell.textLabel.text = [NSString stringWithFormat:@"%@", 
          event.title 
          ]; 
    cell.detailTextLabel.text = [formatter stringFromDate: gmtDate]; 


    return cell; 
} 

@end 
나는이 코드를 온라인으로 발견했지만 그는 JSON으로 데이터를 가져 오지 않지만 iPhone 캘린더에서 나는 믿습니다.

@interface MasterViewController() 

@property (strong, nonatomic) NSMutableDictionary *sections; 
@property (strong, nonatomic) NSArray *sortedDays; 
@property (strong, nonatomic) NSDateFormatter *sectionDateFormatter; 
@property (strong, nonatomic) NSDateFormatter *cellDateFormatter; 

- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate; 
- (NSDate *)dateByAddingYears:(NSInteger)numberOfYears toDate:(NSDate *)inputDate; 

@end 



@implementation MasterViewController 

@synthesize sections; 
@synthesize sortedDays; 
@synthesize sectionDateFormatter; 
@synthesize cellDateFormatter; 


- (void)awakeFromNib 
{ 
    [super awakeFromNib]; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 


#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSDate *now = [NSDate date]; 
    NSDate *startDate = [self dateAtBeginningOfDayForDate:now]; 
    NSDate *endDate = [self dateByAddingYears:1 toDate:startDate]; 

    EKEventStore *eventStore = [[EKEventStore alloc] init]; 
    NSPredicate *searchPredicate = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:nil]; 
    NSArray *events = [eventStore eventsMatchingPredicate:searchPredicate]; 

    self.sections = [NSMutableDictionary dictionary]; 
    for (EKEvent *event in events) 
    { 
     // Reduce event start date to date components (year, month, day) 
     NSDate *dateRepresentingThisDay = [self dateAtBeginningOfDayForDate:event.startDate]; 

     // If we don't yet have an array to hold the events for this day, create one 
     NSMutableArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay]; 
     if (eventsOnThisDay == nil) { 
      eventsOnThisDay = [NSMutableArray array]; 

      // Use the reduced date as dictionary key to later retrieve the event list this day 
      [self.sections setObject:eventsOnThisDay forKey:dateRepresentingThisDay]; 
     } 

     // Add the event to the list for this day 
     [eventsOnThisDay addObject:event]; 
    } 

    // Create a sorted list of days 
    NSArray *unsortedDays = [self.sections allKeys]; 
    self.sortedDays = [unsortedDays sortedArrayUsingSelector:@selector(compare:)]; 

    self.sectionDateFormatter = [[NSDateFormatter alloc] init]; 
    [self.sectionDateFormatter setDateStyle:NSDateFormatterLongStyle]; 
    [self.sectionDateFormatter setTimeStyle:NSDateFormatterNoStyle]; 

    self.cellDateFormatter = [[NSDateFormatter alloc] init]; 
    [self.cellDateFormatter setDateStyle:NSDateFormatterNoStyle]; 
    [self.cellDateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
} 

- (void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 
} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [super viewDidDisappear:animated]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 


#pragma mark - Date Calculations 

- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate 
{ 
    // Use the user's current calendar and time zone 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone]; 
    [calendar setTimeZone:timeZone]; 

    // Selectively convert the date components (year, month, day) of the input date 
    NSDateComponents *dateComps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:inputDate]; 

    // Set the time components manually 
    [dateComps setHour:0]; 
    [dateComps setMinute:0]; 
    [dateComps setSecond:0]; 

    // Convert back  
    NSDate *beginningOfDay = [calendar dateFromComponents:dateComps]; 
    return beginningOfDay; 
} 

- (NSDate *)dateByAddingYears:(NSInteger)numberOfYears toDate:(NSDate *)inputDate 
{ 
    // Use the user's current calendar 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 

    NSDateComponents *dateComps = [[NSDateComponents alloc] init]; 
    [dateComps setYear:numberOfYears]; 

    NSDate *newDate = [calendar dateByAddingComponents:dateComps toDate:inputDate options:0]; 
    return newDate; 
} 


#pragma mark - UITableViewDataSource methods 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [self.sections count]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:section]; 
    NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay]; 
    return [eventsOnThisDay count]; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:section]; 
    return [self.sectionDateFormatter stringFromDate:dateRepresentingThisDay]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *reuseIdentifier = @"EventTitleCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; 

    NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:indexPath.section]; 
    NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay]; 
    EKEvent *event = [eventsOnThisDay objectAtIndex:indexPath.row]; 

    cell.textLabel.text = event.title; 
    if (event.allDay) { 
     cell.detailTextLabel.text = @"all day"; 
    } else { 
     cell.detailTextLabel.text = [self.cellDateFormatter stringFromDate:event.startDate]; 
    } 
    return cell; 
} 

@end 

내 json event.startdate를 섹션 헤더로 사용하는 방법이 있습니까?

답변

0

개인적으로, 나는 당신이하려고하는 것이 아니기 때문에 거기에 두 번째로 게시 한 코드를 무시할 것입니다.

머리글과 자막을 설정하는 코드 부분은 다음 두 줄입니다. cell.textLabel.text = [NSString stringWithFormat : @ "% @", event.title]; cell.detailTextLabel.text = [formatter stringFromDate : gmtDate];

그래서 표제를 날짜로 사용하려면 cell.textLabel.text 값으로 지정하십시오.

+0

그는 셀 제목이 아닌 섹션 헤더에 대해 이야기하고 있습니다. – Mar0ux

+0

하지만 섹션을 만들지는 않습니까? 나는 날짜별로 모든 이벤트를 그룹화하고 싶습니다. 그러나 제 날짜에는 "2013-03-26T20 : 45 : 00.00CET"과 같이 이상한 찾고있는 Google 날짜가 있습니다. – catu

0

섹션을 원한다면.

섹션의 수는 1

그런 다음 당신이이 테이블 방법을 살펴 할 수 있습니다보다 큰 있는지 확인합니다. 정확한 케이스 및 사용자 정의 요구 사항에 따라 적절하게 변경할 수 있습니다.

(NSString*) tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section{ 
    } 

(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{ 
} 

(UIView*)tableView:(UITableView*)table viewForHeaderInSection:(NsInteger)section{ 
} 

이 정보가 도움이되기를 바랍니다. 나는 현재 일반적으로 사용할 수있는 시간이 없다는 예를 들고 싶지만 필요한 경우 제공 할 수 있습니다.

돌보기 :