IOS本地通知实现
當一段時間沒有使用一個APP的時候(例如消消樂, 熊貓讀書等), 其都會自動的跳出一個通知, 告訴你多久沒有用過這個app了,同時提醒你再次使用,目的是為其留住現(xiàn)有的用戶.
本地通知,不像遠程通知還要請求蘋果APNs服務器,其推送消息的過程較為簡單,下面探討下具體的實現(xiàn)原理.
注意:如果蘋果設備是ios8系統(tǒng)以上,需要請求通知,在AppDelegate.m的
<span style="font-size:14px;">- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions</span>這個方法中實現(xiàn)請求通知 <span style="font-size:14px;">//判斷當前設備的系統(tǒng)if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];// 注冊通知類型[application registerUserNotificationSettings:settings];[application registerForRemoteNotifications];}</span>
然后,可以在要實現(xiàn)通知的控制器中,具體實現(xiàn)通知的代碼邏輯
第一步:創(chuàng)建本地通知;
第二步:設置本地通知的附帶信息;
第三步:注冊通知.
其中第二步中,通知的附帶信息有
<span style="font-size:14px;">@property(nonatomic,copy) NSDate *fireDate; 指定通知發(fā)送的時間@property(nonatomic,copy) NSTimeZone *timeZone; 指定發(fā)送通知的時區(qū)@property(nonatomic) NSCalendarUnit repeatInterval; 重復的周期, 枚舉@property(nonatomic,copy) NSCalendar *repeatCalendar; 重復的周期@property(nonatomic,copy) NSString *alertBody; 通知內容@property(nonatomic) BOOL hasAction; 是否需要滑動事件@property(nonatomic,copy) NSString *alertAction; 鎖屏狀態(tài)的標題@property(nonatomic,copy) NSString *alertLaunchImage; 點擊通知之后的啟動圖片@property(nonatomic,copy) NSString *soundName; 收到通知播放的音樂@property(nonatomic) NSInteger applicationIconBadgeNumber; 圖標提醒數(shù)字@property(nonatomic,copy) NSDictionary *userInfo; 額外的信息</span>可以根據(jù)具體的要求,實現(xiàn)相關的信息,具體代碼為: <span style="font-size:14px;"> //1.創(chuàng)建本地通知對象UILocalNotification *note = [[UILocalNotification alloc] init];//1.1指定通知發(fā)送時間note.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];//1.2指定通知內容note.alertBody = @"本地通知測試";//1.3鎖屏狀態(tài)的標題note.alertAction = @"鎖屏信息";//1.4額外的信息note.userInfo = @{@"name":@"xiaoming",@"age":@"24"};//2.注冊通知UIApplication *application = [UIApplication sharedApplication];[application scheduleLocalNotification:note];</span>
當收到通知的信息的時候,系統(tǒng)會執(zhí)行AppDelegate.m中的代理方法 <span style="font-size:14px;">// 接收到本地通知時就會調用 // 當程序在前臺時, 會自動調用該方法 // 當程序 還后臺時, 只有用戶點擊了通知才會調用 //如果應用程序是關閉狀態(tài)會調用didFinishLaunchingWithOptions - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{//獲取通知的數(shù)據(jù)NSLog(@"%@", notification.userInfo); } </span>
當應用程序是關閉狀態(tài)會調用application:didFinishLaunchingWithOptionS
數(shù)據(jù)可以從launchOptions中取出
轉載于:https://www.cnblogs.com/xiaocai-ios/p/7779809.html
總結
- 上一篇: TNonblockingServer 连
- 下一篇: ibatis mybatis传入List