2009-09-21 250 views
2

在iPhone SDK 3.0注册通知,我想对于一个注册通知,当达到一定的时候,它会提醒我的应用程序。可能吗? 感谢在iPhone SDK 3.0

+0

你的意思是推送通知,或NSNotification? NSNotification很容易,但不完全是你需要的。至于推送通知,我从来没有真正掌握过它们。 – 2009-09-21 06:06:29

回答

1

假设你已经在变量date一个NSDate,并希望在该日期就火法dateIsHere:,这样做:

NSTimer* timer = [[NSTimer alloc] initWithFireDate:date 
              interval:0.0f 
              target:self 
              selector:@selector(dateIsHere:) 
              userInfo:nil 
              repeats:NO]; 
[[NSRunLoop mainRunLoop] addTimer:timer 
          forMode:NSDefaultRunLoopMode]; 
[timer release]; 
+0

嗨PeyloW, 我以下面的方式尝试了你的代码,但我得到了一个N​​SInvalidArgumentException.Can你可以告诉我我在这里做什么不正确 ---此代码是在不同的函数内 NSDate * date = [[NSDate alloc ]在里面]; \t日期= [NSDate的日期]; \t的NSTimer *计时器= [[ALLOC的NSTimer] initWithFireDate:日期 \t \t \t \t \t间隔:0。0F \t \t \t \t \t目标:自 \t \t \t \t选择器:@selector(dateIsHere :) \t \t \t \t \t USERINFO:无 \t \t \t \t \t重复:NO]; \t [[NSRunLoop mainRunLoop] addTimer:timer \t \t \t forMode:NSDefaultRunLoopMode]; (无效)dateIsHere { \t NSLog(@“Date is here”); } 谢谢 – felix 2009-09-22 05:09:16

+0

我发现了这个问题。我必须有dateIsHere funtcion lik dateIsHere:(NSTimer *)计时器。我没有包括计时器参数。:) – felix 2009-09-22 05:31:30

0

您将通过设置一个NSTimer开始火在某个日期,并选择该火灾可能是你想要的。不需要使用NSNotifications。

5

建立一个运行选择的NSTimer每30秒(或任何你需要的粒度):

[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; 

-timerFired:选择器(方法)将运行每隔30秒,检查小时,分钟和第二部件,发射一个通知,如果元素匹配所需的时间:

- (void) timerFired:(NSNotification *)notification { 
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
    NSDate *date = [NSDate date]; 
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date]; 
    NSInteger hour = [dateComponents hour]; 
    NSInteger min = [dateComponents minute]; 
    NSInteger sec = [dateComponents second]; 
    if ((hour == kDesiredHour) && (min == kDesiredMinute) && (sec == kDesiredSecond)) { 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"kTimeComponentsWereMatched" object:nil userInfo:nil]; 
    } 
} 

您注册侦听此通知在其他一些地方类:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"kTimeComponentsWereMatched" object:nil]; 

因此,你必须在同一类中的方法,做一些有趣的事情:

- (void) doSomething:(NSNotification *)notification { 
    // do something interesting here... 
} 

如果是在同一个类可以合并该代码。或者在NSTimer中指定target指向要运行selector的类实例。

+0

确实,即使应用程序被关闭这项工作? – cone 2011-08-18 08:27:53

1

我假设您希望此计时器触发,即使应用程序已关闭。您可以使用通知,但您必须拥有发布通知的服务器。

此外,iPhone会拉一个警报,要求用户打开应用程序 - 但他们没有选择这样做。