我正在尝试在我的项目中使用UILocalNotification。我希望我的应用程序在后台每5秒钟(不停止)收到通知。我正在尝试以下代码。安装后,它仅在5秒后第一次通知我的应用程序。我想让它每5秒钟不停地通知。我怎样才能实现它?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
// Initiating notification at app startup
[self InitiateLocalNotification];
return YES;
}
-(void) InitiateLocalNotification
{
NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:5];
UILocalNotification *notify = [ [UILocalNotification alloc] init ];
notify.fireDate = notificationDate;
//notify.applicationIconBadgeNumber = 1;
notify.soundName = UILocalNotificationDefaultSoundName;
notify.timeZone = [NSTimeZone defaultTimeZone];
//notify.alertBody = @"Local notification test";
//notify.repeatInterval = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"notifiValue" forKey:@"notifiKey"];
notify.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:notify];
[notify release];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
}
答案 0 :(得分:1)
你只是在打电话
[self InitiateLocalNotification];
一次,因此只安排一个通知。
您必须安排您希望收到的每个通知(从现在起5秒后安排通知,从现在开始10秒......等),因为您没有对重复间隔进行那种控制。
解决方案是在收到通知时安排下一个通知,但这不会导致通知间隔5秒钟。
答案 1 :(得分:1)
我认为,如果您收到通知,则需要再次注册通知
您的代码可以是:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ // Override point for customization after application launch.
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
// Initiating notification at app startup
[self InitiateLocalNotification];
return YES;
}
-(void) InitiateLocalNotification
{
NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:5];
UILocalNotification *notify = [ [UILocalNotification alloc] init ];
notify.fireDate = notificationDate;
//notify.applicationIconBadgeNumber = 1;
notify.soundName = UILocalNotificationDefaultSoundName;
notify.timeZone = [NSTimeZone defaultTimeZone];
//notify.alertBody = @"Local notification test";
//notify.repeatInterval = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"notifiValue" forKey:@"notifiKey"]; notify.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:notify];
[notify release];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
// Need to register again
[self InitiateLocalNotification];
}