iOS 10 UserNotifications Kit

#define XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8__has_include()

#define SYSTEM_VERSION_EQUAL_TO(v)([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)

#define SYSTEM_VERSION_GREATER_THAN(v)([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

#define SYSTEM_VERSION_LESS_THAN(v)([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

//

#import"ViewController.h"

/// 1. import UserNotifications

///推送通知从UIKit独立出来,成为一个独立的框架。必须导入

///Notification become independent from UIKit

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8

@importUserNotifications;

#endif

staticNSString*constCYLInviteCategoryIdentifier =@"com.elonchan.localNotification";

@interfaceViewController()

@end

@implementationViewController

- (void)triggerNotification:(id)sender {

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

// create actions

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

// create actions

UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:@"com.elonchan.yes"

title:@"Accept"

options:UNNotificationActionOptionForeground];

UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:@"com.elonchan.no"

title:@"Decline"

options:UNNotificationActionOptionDestructive];

UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:@"com.elonchan.snooze"

title:@"Snooze"

options:UNNotificationActionOptionDestructive];

NSArray *notificationActions =@[acceptAction, declineAction, snoozeAction];

// create a category

UNNotificationCategory *inviteCategory = [UNNotificationCategory categoryWithIdentifier:CYLInviteCategoryIdentifier

actions:notificationActions

minimalActions:notificationActions

intentIdentifiers:@[]

options:UNNotificationCategoryOptionCustomDismissAction];

NSSet *categories = [NSSet setWithObject:inviteCategory];

// registration

[center setNotificationCategories:categories];

#endif

}elseif(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {

// create actions

UIMutableUserNotificationAction*acceptAction = [[UIMutableUserNotificationActionalloc]init];

acceptAction.identifier=@"com.elonchan.yes";

acceptAction.title=@"Accept";

acceptAction.activationMode=UIUserNotificationActivationModeBackground;

acceptAction.destructive=NO;

acceptAction.authenticationRequired=NO;//If YES requies passcode, but does not unlock the device

UIMutableUserNotificationAction*declineAction = [[UIMutableUserNotificationActionalloc]init];

declineAction.identifier=@"com.elonchan.no";

acceptAction.title=@"Decline";

acceptAction.activationMode=UIUserNotificationActivationModeBackground;

declineAction.destructive=YES;

acceptAction.authenticationRequired=NO;

UIMutableUserNotificationAction*snoozeAction = [[UIMutableUserNotificationActionalloc]init];

snoozeAction.identifier=@"com.elonchan.snooze";

acceptAction.title=@"Snooze";

snoozeAction.activationMode=UIUserNotificationActivationModeBackground;

snoozeAction.destructive=YES;

snoozeAction.authenticationRequired=NO;

// create a category

UIMutableUserNotificationCategory*inviteCategory = [[UIMutableUserNotificationCategoryalloc]init];

inviteCategory.identifier=CYLInviteCategoryIdentifier;

NSArray*notificationActions =@[acceptAction, declineAction, snoozeAction];

[inviteCategorysetActions:notificationActionsforContext:UIUserNotificationActionContextDefault];

[inviteCategorysetActions:notificationActionsforContext:UIUserNotificationActionContextMinimal];

// registration

NSSet*categories = [NSSetsetWithObject:inviteCategory];

UIUserNotificationTypetypes =UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert;

UIUserNotificationSettings*settings = [UIUserNotificationSettingssettingsForTypes:typescategories:categories];

[[UIApplicationsharedApplication]registerUserNotificationSettings:settings];

}

/// 2. request authorization for localNotification

[selfregisterNotificationSettingsCompletionHandler:^(BOOLgranted,NSError*_Nullableerror) {

if(!error) {

NSLog(@"request authorization succeeded!");

[selfshowAlert];

}

}];

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8

// //Deliver the notification at 08:30 everyday

// NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

// dateComponents.hour = 8;

// dateComponents.minute = 30;

// UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];

UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];

content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:"arguments:nil];

content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let's play with Jerry!"

arguments:nil];

content.sound = [UNNotificationSound defaultSound];

content.categoryIdentifier =@"com.elonchan.localNotification";

/// 4. update application icon badge number

content.badge =@([[UIApplication sharedApplication] applicationIconBadgeNumber] +1);

content.launchImageName =@"any string is ok,such as微博@iOS程序犭袁";

// Deliver the notification in five seconds.

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger

triggerWithTimeInterval:5.frepeats:YES];

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"

content:content trigger:trigger];

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

/// 3. schedule localNotification,The delegate must be set before the application returns from applicationDidFinishLaunching:.

// center.delegate = self;

[center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullableerror) {

if(!error) {

NSLog(@"add NotificationRequest succeeded!");

}

}];

#endif

}else{

/// 3. schedule localNotification

UILocalNotification*localNotification = [[UILocalNotificationalloc]init];

localNotification.fireDate= [NSDatedateWithTimeIntervalSinceNow:5.f];

localNotification.alertTitle=@"Elon said:";

localNotification.alertBody=@"Hello Tom!Get up, let's play with Jerry!";

localNotification.alertAction=@"play with Jerry";

//Identifies the image used as the launch image when the user taps (or slides) the action button (or slider).

localNotification.alertLaunchImage=@"LaunchImage.png";

localNotification.userInfo=@{@"CategoryIdentifier":CYLInviteCategoryIdentifier};

localNotification.timeZone= [NSTimeZonedefaultTimeZone];

//repeat evey minute,0 means don't repeat

localNotification.repeatInterval=NSCalendarUnitMinute;

/// 4. update application icon badge number

localNotification.applicationIconBadgeNumber= [[UIApplicationsharedApplication]applicationIconBadgeNumber] +1;

[[UIApplicationsharedApplication]scheduleLocalNotification:localNotification];

[selfshowAlert];

}

}

- (void)registerNotificationSettingsCompletionHandler:(void(^)(BOOLgranted,NSError*__nullableerror))completionHandler; {

/// 2. request authorization for localNotification

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)

completionHandler:completionHandler];

#endif

}elseif(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")){

UIUserNotificationSettings*userNotificationSettings = [UIUserNotificationSettingssettingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeSound|UIUserNotificationTypeBadge)

categories:nil];

UIApplication*application = [UIApplicationsharedApplication];

[applicationregisterUserNotificationSettings:userNotificationSettings];

//FIXME:

// !completionHandler ?: completionHandler(granted, error);

}

}

- (void)stopNotification:(id)sender {

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

// remove all local notification:

[center removeAllPendingNotificationRequests];

// or you can remove specifical local notification:

//[center removePendingNotificationRequestsWithIdentifiers:@[ CYLInviteCategoryIdentifier ]];

#endif

}else{

// remove all local notification:

[[UIApplicationsharedApplication]cancelAllLocalNotifications];

// or you can remove specifical local notification:

//NSString *specificalIDToCancel = CYLInviteCategoryIdentifier;

//UILocalNotification *notificationToCancel = nil;

//for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {

//if([[aNotif.userInfo objectForKey:@"CategoryIdentifier"] isEqualToString:specificalIDToCancel]) {

//notificationToCancel = aNotif;

//break;

//}

//}

//if(notificationToCancel) {

//[[UIApplication sharedApplication] cancelLocalNotification:notificationToCancel];

//}

}

}

- (void)addLabel:(NSString*)title backgroundColor:(UIColor*)backgroundColor {

UILabel*label = [[UILabelalloc]init];

label.numberOfLines=0;

label.backgroundColor= backgroundColor;

label.text= title;

label.textColor= [UIColorblackColor];

[labelsizeToFit];

label.center=CGPointMake([UIScreenmainScreen].bounds.size.width*0.5,arc4random_uniform([UIScreenmainScreen].bounds.size.height));

[self.viewaddSubview:label];

}

//TODO:

//- (void)handleActionWithIdentifier:(NSString *)identifier

//forLocalNotification:(UILocalNotification *)localNotification {

//

//}

- (void)showAlert {

UIAlertView*alert = [[UIAlertViewalloc]initWithTitle:nil

message:@"please enter background now"

delegate:self

cancelButtonTitle:nil

otherButtonTitles:nil];

[alertshow];

intdelayInSeconds =1;

dispatch_time_twhen =dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds *NSEC_PER_SEC));

dispatch_after(when,dispatch_get_main_queue(), ^{

[alertdismissWithClickedButtonIndex:0animated:YES];

});

}

- (void)viewDidLoad {

[superviewDidLoad];

UIButton*triggerButton = [selfbuttonWithY:([UIScreenmainScreen].bounds.size.width*.5-50)title:@"Click me to trigger localNotification"backgroundColor:[UIColorcolorWithRed:(51) /255.fgreen:(171) /255.fblue:(160) /255.falpha:1.f]];

[triggerButtonaddTarget:selfaction:@selector(triggerNotification:)forControlEvents:UIControlEventTouchUpInside];

[self.viewaddSubview:triggerButton];

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

UIButton*stopButton = [selfbuttonWithY:([UIScreenmainScreen].bounds.size.width*.5+50)title:@"Click me to stop localNotification"backgroundColor:[UIColorredColor]];

[stopButtonaddTarget:selfaction:@selector(stopNotification:)forControlEvents:UIControlEventTouchUpInside];

[self.viewaddSubview:stopButton];

}

}

- (UIButton*)buttonWithY:(CGFloat)Y title:(NSString*)title backgroundColor:(UIColor*)color {

UIButton*button = [UIButtonbuttonWithType:UIButtonTypeCustom];

button.backgroundColor= color;

button.frame= ({

CGRectframe = button.frame;

frame.size.width= [UIScreenmainScreen].bounds.size.width-10;

frame.size.height=40;

frame;

});

button.center=CGPointMake([UIScreenmainScreen].bounds.size.width*.5, Y);

[buttonsetTitle:titleforState:UIControlStateNormal];

button.layer.shadowColor= [UIColorgrayColor].CGColor;

button.layer.cornerRadius=6.0;

button.titleLabel.font= [UIFontboldSystemFontOfSize:15];

button.titleLabel.textAlignment=NSTextAlignmentCenter;

[buttonsetTitleColor:[UIColorblackColor]forState:UIControlStateHighlighted];

returnbutton;

}

@end

你可能感兴趣的:(iOS 10 UserNotifications Kit)