[英]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。 尚不清楚您的应用程序是否在需要此通知时正在运行,但是无论哪种情况,此类都应使您指向正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.