每周二本地通知重复间隔不起作用..我错过了什么?

时间:2014-01-19 14:17:53

标签: ios objective-c cocoa-touch uilocalnotification repeat

所以,我知道星期一是= 2,当我说tuesaday = 3它不会被解雇时。

要么我没有正确设置日期,要么NSWeekCalendarUnit的{​​{1}}和calendar components错误!

现在我的奇迹是: 从周日开始,repeatinterval是否等于day components1

也应该是7或我做得对吗?

看看我的代码,看看你是否可以修复它。感谢

NSDayCalendarUnit

更新

这是我得到的日志:

-(void) tuesday {   // every tuesday
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];

NSDateComponents *components = [calendar components:NSWeekCalendarUnit fromDate:[NSDate date]];

components.day = 1;
components.hour   = 18;
components.minute = 55;
components.second = 45;

NSDate *fireDate = [calendar dateFromComponents:components];
NSLog(@"Tuesday %@", fireDate);

UILocalNotification *notif = [[UILocalNotification alloc]  init] ;
if (notif == nil)
    return;

notif.fireDate = fireDate;
notif.repeatInterval= NSWeekCalendarUnit ;
notif.soundName = @"ring.wav";
notif.alertBody = [NSString stringWithFormat: @"Hello World"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}

1 个答案:

答案 0 :(得分:0)

您的问题似乎是,您将组件添加到NSDate,而不设置相关的日期参数。要触发通知,您需要在下周二定义NSDate。

希望这个例子对你有所帮助:

//first you have to check what's the current weekday
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

//Set timezone if needed
gregorian.timeZone  = [NSTimeZone timeZoneForSecondsFromGMT:0];

NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int currentWeekday = [comps weekday] ;
NSLog(@"currentWeekDay:%d", currentWeekday);


//After you know which weekday it is, you can check how many days to add till tuesday

int daysToAdd;
switch (currentWeekday) {
        //Sunday to Tuesday
    case 1:
        daysToAdd = 2;
        break;

        //Monday to Tuesday
    case 2:
        daysToAdd = 1;
        break;

        //Tuesday to Tuesday
    case 3:
        daysToAdd = 0;
        break;

        //Wednesday to Tuesday
    case 4:
        daysToAdd = 6;
        break;

        //Thursday to Tuesday
    case 5:
        daysToAdd = 5;
        break;

        //Thursday to Tuesday
    case 6:
        daysToAdd = 4;
        break;

    case 7:
        daysToAdd = 3;
        break;

    default:
        daysToAdd = 0;
        break;
}

NSDate *firetime = [[NSDate alloc] init];
NSDateComponents *timeCorrection = [[NSDateComponents alloc] init];
[timeCorrection setHour:18];
[timeCorrection setMinute:55];
[timeCorrection setSecond:45];
firetime = [[NSCalendar currentCalendar] dateByAddingComponents:timeCorrection toDate:firetime options:0];

NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:daysToAdd];
firetime = [gregorian dateByAddingComponents:offsetComponents toDate:firetime options:0];

//this should be your fire date
NSLog(@"Next tuesday:%@",firetime);

希望这是您正在寻找的,或者给您正确的提示。尚未测试过。

格尔茨, Zarakas