簡體   English   中英

在iPhone應用程序中,當一天中的特定時間到達時,如何獲得通知?

[英]How can I get notified when it reaches a certain time of day in an iPhone application?

我正在開發需要在特定時間(准確地說是每小時15分鍾)被調用方法的應用程序。 有沒有辦法在不消耗大量CPU和電池壽命的情況下實現這一目標? 我嘗試搜索,但找不到任何答案。

他們使這變得非常容易。 分配一個NSTimer並使用以下日期將其初始化:

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

然后使用以下命令將其添加到運行循環中:

-(void)addTimer:(NSTimer *)aTimer forMode:(NSString *)mode

在運行循環中,例如[NSRunLoop currentRunLoop] 不知道這是否會喚醒設備或阻止其進入睡眠狀態。

編輯一些示例代碼

// start in 5 minutes
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:300];

// fire every minute from then on
NSTimer *t = [[NSTimer alloc]
    initWithFireDate:date
    interval:60
    target:self
    selector:@selector(stuff:) // -(void)stuff:(NSTimer*)theTimer
    userInfo:nil
    repeats:YES
];

// make it work
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];

-(void)stuff:(NSTimer*)theTimer
{
    if ( done ) [theTimer invalidate];
}

如果您需要在應用程序不運行時發生這種情況,請查看iOS 4.0中的UILocalNotification。 尚不清楚您的應用程序是否在需要此通知時正在運行,但是無論哪種情況,此類都應使您指向正確的方向。

http://developer.apple.com/iphone/library/documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html#//apple_ref/occ/cl/UILocalNotification

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM