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獨(dú)立出來(lái)肤京,成為一個(gè)獨(dú)立的框架。必須導(dǎo)入

///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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末哩照,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子忱屑,更是在濱河造成了極大的恐慌波丰,老刑警劉巖壳坪,帶你破解...
    沈念sama閱讀 221,635評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異掰烟,居然都是意外死亡爽蝴,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)纫骑,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蝎亚,“玉大人,你說(shuō)我怎么就攤上這事先馆》⒖颍” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,083評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵煤墙,是天一觀的道長(zhǎng)梅惯。 經(jīng)常有香客問(wèn)我,道長(zhǎng)仿野,這世上最難降的妖魔是什么铣减? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,640評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮脚作,結(jié)果婚禮上葫哗,老公的妹妹穿的比我還像新娘。我一直安慰自己球涛,他們只是感情好劣针,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著亿扁,像睡著了一般酿秸。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上魏烫,一...
    開(kāi)封第一講書(shū)人閱讀 52,262評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音肝箱,去河邊找鬼哄褒。 笑死,一個(gè)胖子當(dāng)著我的面吹牛煌张,可吹牛的內(nèi)容都是我干的呐赡。 我是一名探鬼主播,決...
    沈念sama閱讀 40,833評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼骏融,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼链嘀!你這毒婦竟也來(lái)了萌狂?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,736評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤怀泊,失蹤者是張志新(化名)和其女友劉穎茫藏,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體霹琼,經(jīng)...
    沈念sama閱讀 46,280評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡务傲,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了枣申。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片售葡。...
    茶點(diǎn)故事閱讀 40,503評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖忠藤,靈堂內(nèi)的尸體忽然破棺而出挟伙,到底是詐尸還是另有隱情,我是刑警寧澤模孩,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布尖阔,位于F島的核電站,受9級(jí)特大地震影響瓜贾,放射性物質(zhì)發(fā)生泄漏诺祸。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評(píng)論 3 333
  • 文/蒙蒙 一祭芦、第九天 我趴在偏房一處隱蔽的房頂上張望筷笨。 院中可真熱鬧,春花似錦龟劲、人聲如沸胃夏。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,340評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)仰禀。三九已至,卻和暖如春蚕愤,著一層夾襖步出監(jiān)牢的瞬間答恶,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,460評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工萍诱, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留悬嗓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,909評(píng)論 3 376
  • 正文 我出身青樓裕坊,卻偏偏與公主長(zhǎng)得像包竹,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容