2013-07-05 2 views
1

매 시간 (오전 6시, 오전 7시, 오전 8시 등)에 일정이 잡힐 이벤트가 있습니다. 내가 함께 performselectors 연쇄를 고려하고 있었지만 그건 그냥 꽤 janky 것 같습니다. 타이머를 예약하는 것은 논리적 인 단계처럼 보이지만 타이머는 매 시간마다 TOP이어야합니다.특정 날짜/시간에 대한 선택기 예약

예를 들어 3:48부터 시작한 경우 이벤트가 4:00에 실행되고 5:00에 다시 시작되고 4:48 및 5:48에 실행되지 않을 것으로 예상됩니다.

제안 사항?

답변

2

첫 번째 트릭은 원하는 날짜를 얻는 것입니다.

-(NSDate*)dateAtHour:(NSInteger)hour { 

NSDate *localDate = [self toLocal]; 
NSDateComponents *comps = [[NSCalendar currentCalendar] 
          components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit 
          fromDate:localDate]; 
comps.hour = hour; 
comps.minute = 0; 
comps.second = 0; 

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; 
NSDate *date = [gregorian dateFromComponents:comps]; 

return [date toUTC]; 

}

-(NSDate *) toLocal { 
NSTimeZone *tz = [NSTimeZone localTimeZone]; 
NSInteger seconds = [tz secondsFromGMTForDate: self]; 
return [NSDate dateWithTimeInterval: seconds sinceDate: self]; 

}

-(NSDate *) toUTC { 
NSTimeZone *tz = [NSTimeZone timeZoneWithName:@"UTC"]; 
NSInteger seconds = [tz secondsFromGMTForDate: self]; 
return [NSDate dateWithTimeInterval: seconds sinceDate: self]; 

}

그런 다음 당신은 단지에 대한 NSTimer을 예약 할 필요가 : 여기 당신이해야 할 수도 있습니다 무엇을 같은 예입니다 특정 날짜/시간 :

- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats 

그러나 앱이 배경에있을 수 있습니다. 이 경우 앱이 전경에있는 동안이 시간별 문제가 발생하기를 원한다고 가정합니다. 이 경우 타이머를 앱 위임의 '시작'메소드 중 하나에서 설정하십시오.

+0

toLocal? toUTC? 이 방법을 어디에서 얻고 있습니까? 또는 당신은 이것이 fleshed 될 것이라고 가정하고 있습니다. (또한, 감사합니다 : - D) –

+0

+1 날짜 구성 요소를 사용하여 NSTimer에 대한,하지만 당신은 U 앞에서에만 응용 프로그램을 실행하고 싶지 생각해야합니까? –

+0

우, 내가 서둘렀다 고 생각해. dateAtHour는 NSDate의 카테고리입니다. toLocal 및 toUTC를 제거 할 수 있으며 시간대 지원이 필요한 경우 내 편집을 참조하십시오. – ax123man

3

이러한 방식으로 선택기를 예약하면 좋지 않습니다. 대신 local notification을 예약 할 수 있습니다. 이렇게하면 응용 프로그램이 백그라운드로 설정되어 있어도 일정을 예약 할 수 있습니다.

UILocalNotification *notification = [[UILocalNotification alloc] init]; 
notification.fireDate = [NSDate dateWithTimeIntervalSince1970:1373050800]; 
notification.userInfo = @{@"key" : @"some contextual info on what to do"}; 
notification.alertBody = @"Hello, it's 2pm!"; 
notification.alertAction = @"Details"; 

[[UIApplication sharedApplication] scheduleLocalNotification:notification]; 
관련 문제