我有代碼設置多個UILocalNotifications
在接下來的幾個星期。 在我的didFinishLaunchingWithOptions
我有代碼請求權限發送通知,然後我有我的代碼來設置我的通知。UILocalNotification不發送通知
但儘管如此,該代碼將返回錯誤:
Haven't received permission from the user to display alerts
我認爲這是試圖運行的通知代碼之前,用戶可以批准許可。
如何讓我的通知代碼僅在用戶說好的時候才能運行以接收通知?
這裏是我的代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FirstTimeBool"]==nil) {
[defaults setObject:@"YES" forKey:@"FirstTimeBool"];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, yyyy"];
NSString* path = [[NSBundle mainBundle] pathForResource:@"example"
ofType:@"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSArray* allLinedStrings = [content componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
for (int i = 0; i < allLinedStrings.count; i++) {
NSString* strsInOneLine = [allLinedStrings objectAtIndex:i];
NSArray* singleStrs = [strsInOneLine componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@";"]];
NSString *date = [singleStrs objectAtIndex:0];
NSDate *eventDate = [dateFormatter dateFromString:date];
if ([today compare:eventDate] == NSOrderedAscending) {
for (int j = 1; j < singleStrs.count; j+=2) {
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.fireDate = [NSDate dateWithTimeInterval:60*60*-24 sinceDate:eventDate];
notification.alertBody = [singleStrs objectAtIndex:j+1];
notification.alertTitle = [singleStrs objectAtIndex:j];
notification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication]scheduleLocalNotification:notification];
}
}
}
}
// Override point for customization after application launch.
return YES;
}
嘗試使用應用程序:didRegisterUserNotificationSettings:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/index.html#//apple_ref/occ/intfm/UIApplicationDelegate/application:didRegisterUserNotificationSettings: –
只是使用本教程來實現本地或遠程通知:http://stackoverflow.com/questions/6047117/how-to-create-local-notifications-in-iphone-app –