2013-03-26 1 views
1

특정 날짜에 UILocalNotification을 발사하고 싶습니다. 이 코드를 사용하는 경우 :특정 날짜의 화재 UILocalNotification

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *components = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]]; 

[components setHour:4]; 
[components setMinute:0]; 

NSDate *fireDate = [gregorian dateFromComponents:components]; 

지금은 오후 3시이면 제대로 작동하지만 예를 들어 오후 5 시가되면 작동하지 않습니다.

어떻게 통지 발사 일을 "다음 4 pm"으로 설정할 수 있습니까? 24 시간 형식의 코드를 다음

+0

은 : - 당신은 자동으로 경보를 매 시간마다 반복합니다 있습니까? 어떻게 알람을 설정 하시겠습니까? –

+1

저는 특정 시간에만 사용자가 앱에서 할 수있는 일을 알리고 자합니다. 알림을 반복해서는 안됩니다. 답장을 보내 주셔서 감사합니다. – Lolloz89

+0

내가 알기로는 특정 시간에 매일 알림을 반복하고 싶습니까? –

답변

4
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *components = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]]; 

[components setHour:4]; 
[components setMinute:0]; 

NSDate *fireDate = [gregorian dateFromComponents:components]; 
NSLog(@"Fire date : %@",fireDate);// Today 4pm is already passed. So you wont get notification 

// You need to check if the time is already passed 
if ([fireDate compare:[NSDate date]] == NSOrderedAscending) 
{ 
    // Schedule it for next day 4pm 
    components.day = components.day+1; 
    fireDate = [gregorian dateFromComponents:components]; 
} 
NSLog(@"Fire date : %@",fireDate); 
+0

이것은 좋은 생각 인 것 같습니다.하지만 30을 components.day로 설정하면 2 월이됩니다. 구성 요소의 날짜가 3 월 1 일 또는 2 월 반환합니까? – Lolloz89

+0

FEB의 경우'components.day'를 30으로 설정할 기회가 없습니다. 날짜가 지나면 하루에 하루를 추가하는 것입니다. 이제 날짜가'components.day'에 하나를 더한 후 오후 5시에 feb28이라고 가정하면 Feb29가 아닌 Mar1st가됩니다. 시스템 시간을 변경하여 확인하십시오. –

+0

좋습니다.이 코드를 사용해 보겠습니다. 작동한다면 답변을 수락합니다. 감사! – Lolloz89

1

시도 : -

NSDate *date = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; 
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date]; 
[components setHour:16]; 
[components setMinute:0]; 
[components setSecond:0]; 

NSDate *newDate = [gregorian dateFromComponents: components]; 
[gregorian release];  

UILocalNotification *localNotif = [[UILocalNotification alloc] init]; 
localNotif.fireDate = newDate; 
localNotif.alertBody = [NSString stringWithFormat:@"Alarm for time : %@",newDate]; 
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
[localNotif release]; 
+0

오후 5 시가되면 미안하지만,이 코드는 그 순간보다 일찍하지만 한 시간 앞선 날짜를 만듭니다. 따라서 알림이 표시되지 않을 것이라고 나는 믿습니다. – Lolloz89

+0

@ Lolloz89 : - 당신 말이 맞아요. 그러나 다시 테스트하려면 장치 시간과 날짜를 원하는대로 설정할 수 있습니다. –