【发布时间】:2012-01-22 04:17:43
【问题描述】:
我正在编写一个应用程序,当活动日期临近时,它会通过通知中心向用户发送警报。但是当我在日期选择器中设置日期并关闭应用程序时,通知不会出现。我已经在我的配置文件中启用了推送通知。这是我项目中处理通知中心的所有代码,这是我的视图控制器文件中处理日期选择器的所有代码:
- (IBAction)dateChanged:(id)sender
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *selectedDate = [self.datePicker date];
[defaults setObject:selectedDate forKey:@"ImportantDatesViewController.selectedDate"];
[defaults synchronize];
}
- (void)viewDidLoad {
NSDate *storedDate = [[NSUserDefaults standardUserDefaults]
objectForKey:@"ImportantDatesViewController.selectedDate"];
if (storedDate == nil) {
storedDate = [NSDate date];
}
[self.datePicker setDate:storedDate animated:NO];
}
这就是我的 App 委托中处理本地通知的所有内容:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm'/'dd'/'yyyy"];
NSDate *eventDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"ImportantDatesViewController.selectedDate"];
localNotif.fireDate = [eventDate dateByAddingTimeInterval:-13*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = @"Event in three days!";
localNotif.alertAction = nil;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
return YES;
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSString* pushToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:@"<"withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"%@", pushToken);
}
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
NSLog(@"error: %@", error);
}
非常感谢任何帮助,谢谢!
【问题讨论】:
-
当我说我在从
NSUserDefaults检索时使用键中的笔尖名称时,恐怕我可能对另一个问题感到困惑。这是个人喜好的问题,以确保密钥是唯一的。事情的真相是你应该使用你用来存储它的任何东西来检索它。找到您存储eventDate的位置并使用相同的密钥。 -
非常感谢马克。我正在尝试确定将 eventDate 存储在哪里,但是在查找它时遇到了一些问题。它可能在我笔尖的选择器中吗?
-
您在哪个视图控制器中向用户询问您要触发本地通知的日期?在那个班级的某个地方,您将日期存储到
NSUserDefaults。使用相同的密钥。现在你明白为什么我提到将键存储为常量了。 :) -
哦,好的,非常感谢。那么,只有在应用程序根本没有运行时才会出现警报,即使在后台也是如此?抱歉这个愚蠢的问题,我对此还是很陌生。
标签: iphone ios xcode notifications local