iOS本地通知實現(xiàn)思路

最近忙畢業(yè)的事情逗栽,到了6月底才忙完胶果,剛畢業(yè),然后又是公司推新版本漾根,很累很騷硼讽,所以到現(xiàn)在才有時間更新博客巢价,其實也是因為大部分時間拿去玩王者榮耀了,辣雞游戲固阁,大家千萬別玩??
今天講講在做公司新版本的時候壤躲,需要實現(xiàn)本地倒計時通知用戶的需求,因為之前沒有做過本地推送备燃,正好把這個分享一下碉克。

本地推送(UNUserNotificationCenter,UILocalNotification)

首先要了解一下在iOS10以上,我們使用UNUserNotificationCenter來實現(xiàn)本地推送
在iOS8以上并齐,我們使用UILocalNotification來實現(xiàn)本地推送

UNUserNotificationCenter

__IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
@interface UNMutableNotificationContent : UNNotificationContent

// Optional array of attachments.
@property (NS_NONATOMIC_IOSONLY, copy) NSArray <UNNotificationAttachment *> *attachments __TVOS_PROHIBITED;

// The application badge number. nil means no change. 0 to hide.
// 通知對應(yīng)的app圖標(biāo)的紅點數(shù)量漏麦,nil意味著沒有改變,0就隱藏紅點
@property (NS_NONATOMIC_IOSONLY, copy, nullable) NSNumber *badge;

// The body of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
//通知的內(nèi)容體况褪,通常使用[NSString localizedUserNotificationStringForKey:arguments:NSString]傳入一個NSString字符串撕贞,從而展示通知的內(nèi)容
@property (NS_NONATOMIC_IOSONLY, copy) NSString *body __TVOS_PROHIBITED;

// The identifier for a registered UNNotificationCategory that will be used to determine the appropriate actions to display for the notification.
//和UITableViewCell類似的標(biāo)識符,可以用通過UNNotificationCategory來判斷测垛,從而對通知執(zhí)行不同操作
@property (NS_NONATOMIC_IOSONLY, copy) NSString *categoryIdentifier __TVOS_PROHIBITED;

// The launch image that will be used when the app is opened from the notification.
//通知開啟的啟動照片
@property (NS_NONATOMIC_IOSONLY, copy) NSString *launchImageName __TVOS_PROHIBITED;

// The sound that will be played for the notification.
//通知的提示聲音
@property (NS_NONATOMIC_IOSONLY, copy, nullable) UNNotificationSound *sound __TVOS_PROHIBITED;

// The subtitle of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
//通知的副標(biāo)題捏膨,也是用[NSString localizedUserNotificationStringForKey:arguments:]來初始化
@property (NS_NONATOMIC_IOSONLY, copy) NSString *subtitle __TVOS_PROHIBITED;

// The unique identifier for the thread or conversation related to this notification request. It will be used to visually group notifications together.
//對一個通知請求的標(biāo)識符,通呈澄辏可以用于管理多個通知
@property (NS_NONATOMIC_IOSONLY, copy) NSString *threadIdentifier __TVOS_PROHIBITED;

// The title of the notification. Use -[NSString localizedUserNotificationStringForKey:arguments:] to provide a string that will be localized at the time that the notification is presented.
//通知的標(biāo)題号涯,用[NSString localizedUserNotificationStringForKey:arguments:]來初始化
@property (NS_NONATOMIC_IOSONLY, copy) NSString *title __TVOS_PROHIBITED;

// Apps can set the userInfo for locally scheduled notification requests. The contents of the push payload will be set as the userInfo for remote notifications.
//通知傳遞的數(shù)據(jù),和NSNotification一樣
@property (NS_NONATOMIC_IOSONLY, copy) NSDictionary *userInfo;

@end

UILocalNotification

@interface UILocalNotification : NSObject<NSCopying, NSCoding>

- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

// timer-based scheduling
// 通知開啟的時間锯七,使用NSDate來設(shè)置
@property(nullable, nonatomic,copy) NSDate *fireDate;
// the time zone to interpret fireDate in. pass nil if fireDate is an absolute GMT time (e.g. for an egg timer).
// pass a time zone to interpret fireDate as a wall time to be adjusted automatically upon time zone changes (e.g. for an alarm clock).
//對應(yīng)所在的時區(qū)链快,通常用[NSTimeZone localTimeZone]
@property(nullable, nonatomic,copy) NSTimeZone *timeZone;
//重復(fù)時間的方式
@property(nonatomic) NSCalendarUnit repeatInterval;      // 0 means don't repeat
//重復(fù)時間的時間
@property(nullable, nonatomic,copy) NSCalendar *repeatCalendar;

// location-based scheduling

// set a CLRegion object to trigger the notification when the user enters or leaves a geographic region, depending upon the properties set on the CLRegion object itself. registering multiple UILocalNotifications with different regions containing the same identifier will result in undefined behavior. the number of region-triggered UILocalNotifications that may be registered at any one time is internally limited. in order to use region-triggered notifications, applications must have "when-in-use" authorization through CoreLocation. see the CoreLocation documentation for more information.
// 設(shè)置一個位置區(qū)域,當(dāng)用戶進(jìn)入或者離開一個區(qū)域的時候眉尸,會觸發(fā)推送域蜗,使用的時候記得設(shè)置關(guān)于定位的權(quán)限
@property(nullable, nonatomic,copy) CLRegion *region NS_AVAILABLE_IOS(8_0);

// when YES, the notification will only fire one time. when NO, the notification will fire every time the region is entered or exited (depending upon the CLRegion object's configuration). default is YES.
// 設(shè)置通過位置觸發(fā)的通知次數(shù)是不是只有一次巨双,默認(rèn)是YES
@property(nonatomic,assign) BOOL regionTriggersOnce NS_AVAILABLE_IOS(8_0);

// alerts
// 通知的內(nèi)容體
@property(nullable, nonatomic,copy) NSString *alertBody;      // defaults to nil. pass a string or localized string key to show an alert
// 是否有按鈕,默認(rèn)是有
@property(nonatomic) BOOL hasAction;                // defaults to YES. pass NO to hide launching button/slider
// 提示按鈕的文字
@property(nullable, nonatomic,copy) NSString *alertAction;    // used in UIAlert button or 'slide to unlock...' slider in place of unlock
// 提示按鈕的啟動頁路徑
@property(nullable, nonatomic,copy) NSString *alertLaunchImage;   // used as the launch image (UILaunchImageFile) when launch button is tapped
// 通知的標(biāo)題
@property(nullable, nonatomic,copy) NSString *alertTitle NS_AVAILABLE_IOS(8_2);  // defaults to nil. pass a string or localized string key

// sound
// 通知的音頻名字
@property(nullable, nonatomic,copy) NSString *soundName;      // name of resource in app's bundle to play or UILocalNotificationDefaultSoundName

// badge
// 通知的紅點
@property(nonatomic) NSInteger applicationIconBadgeNumber;  // 0 means no change. defaults to 0

// user info
// 通知的數(shù)據(jù)
@property(nullable, nonatomic,copy) NSDictionary *userInfo;   // throws if contains non-property list types

// category identifer of the local notification, as set on a UIUserNotificationCategory and passed to +[UIUserNotificationSettings settingsForTypes:categories:]
@property (nullable, nonatomic, copy) NSString *category NS_AVAILABLE_IOS(8_0);

@end

代碼實踐(業(yè)務(wù)場景是在開啟時間5分鐘前本地推送提示用戶)

//首先引入頭文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
if([[UIDevice currentDevice].systemVersion floatValue] >= 10.0f) {
        // 使用 UNUserNotificationCenter 來管理通知
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        
        //需創(chuàng)建一個包含待通知內(nèi)容的 UNMutableNotificationContent 對象霉祸,注意不是 UNNotificationContent ,此對象為不可變對象炉峰。
        UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
        content.title = [NSString localizedUserNotificationStringForKey:@"APP_NAME" arguments:nil];
        content.body = [NSString localizedUserNotificationStringForKey:[NSString stringWithFormat:@"【APP_NAME %@】 5分鐘后開始搶標(biāo)",self.model.title]
                                                             arguments:nil];
        content.sound = [UNNotificationSound defaultSound];
        content.userInfo = @{
                            //對應(yīng)的數(shù)據(jù)參數(shù)
                             };
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date = [dateFormatter dateFromString:self.model.startTime];
        NSTimeInterval startTimeInterval = [date timeIntervalSinceDate:[NSDate date]];
        
        // 在發(fā)售時間的5分鐘前 推送本地推送
        UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:startTimeInterval - 5 * 60 repeats:NO];
        
        UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveMethod"
                                                                              content:content
                                                                              trigger:trigger];
        
        //添加推送成功后的處理!
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            //推送失敗的話 提示用戶
            if(error) {
                //提示用戶
                
                return ;
            }
            
            //推送成功的話 提示使用者并且更新UI
        }];
    } else if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0f){
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        // 設(shè)置觸發(fā)通知的時間
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        dateFormatter.timeZone = [NSTimeZone localTimeZone];
        NSDate *date = [dateFormatter dateFromString:self.model.startTime];
        
        NSDate *fireDate = [NSDate dateWithTimeInterval:-5 * 60 sinceDate:date];
        
        notification.fireDate = fireDate;
        // 時區(qū)
        notification.timeZone = [NSTimeZone defaultTimeZone];
        // 設(shè)置重復(fù)的間隔
        notification.repeatInterval = kCFCalendarUnitSecond;
        
        // 通知內(nèi)容
        notification.alertBody = [NSString stringWithFormat:@"【APP_NAME %@】 5分鐘后開始搶標(biāo)",self.model.title];
        notification.alertTitle = @"APP_NAME";
        notification.applicationIconBadgeNumber = 1;
        // 通知被觸發(fā)時播放的聲音
        notification.soundName = UILocalNotificationDefaultSoundName;
        // 通知參數(shù)
        notification.userInfo = @{
                                //對應(yīng)的數(shù)據(jù)參數(shù)
                                  };
        
        // ios8后脉执,需要添加這個注冊疼阔,才能得到授權(quán)
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                     categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            // 通知重復(fù)提示的單位,可以是天半夷、周婆廊、月
            notification.repeatInterval = 0;
        }
        
        // 執(zhí)行通知注冊
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        
        //推送成功的話 提示用戶
        });
    }
//回調(diào)處理
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    //iOS8版本下的處理
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //遠(yuǎn)程通知
        
    }
    else {
        // 判斷為本地通知
        //iOS10下面處理
    }
    
    completionHandler();  // 系統(tǒng)要求執(zhí)行這個方法
}

總結(jié)

本地通知其實和遠(yuǎn)程通知差不多,唯一要小心的就是代碼中不要加上移除本地通知的代碼巫橄,不然會導(dǎo)致本地通知的通知不正常
[[UIApplication sharedApplication] cancelAllLocalNotifications]
或者
[[UIApplication sharedApplication] cancelLocalNotification:(UILocalNotification *)notification]
因為公司之前是使用極光推送的淘邻,所以上面代碼中的iOS10回調(diào)是JPush封裝好的回調(diào),如果不是使用極光推送的開發(fā)者湘换,則是在UNUserNotificationCenterDelegate的中處理回調(diào)即可

@protocol UNUserNotificationCenterDelegate <NSObject>

@optional

// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);

// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0) __TVOS_PROHIBITED;

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末宾舅,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子彩倚,更是在濱河造成了極大的恐慌筹我,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件帆离,死亡現(xiàn)場離奇詭異蔬蕊,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)哥谷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進(jìn)店門岸夯,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人们妥,你說我怎么就攤上這事猜扮。” “怎么了监婶?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵旅赢,是天一觀的道長。 經(jīng)常有香客問我压储,道長鲜漩,這世上最難降的妖魔是什么源譬? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任集惋,我火速辦了婚禮,結(jié)果婚禮上踩娘,老公的妹妹穿的比我還像新娘刮刑。我一直安慰自己喉祭,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布雷绢。 她就那樣靜靜地躺著泛烙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪翘紊。 梳的紋絲不亂的頭發(fā)上蔽氨,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天,我揣著相機(jī)與錄音帆疟,去河邊找鬼鹉究。 笑死,一個胖子當(dāng)著我的面吹牛踪宠,可吹牛的內(nèi)容都是我干的自赔。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼柳琢,長吁一口氣:“原來是場噩夢啊……” “哼绍妨!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起柬脸,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤他去,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后倒堕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體孤页,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年涩馆,在試婚紗的時候發(fā)現(xiàn)自己被綠了行施。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡魂那,死狀恐怖蛾号,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情涯雅,我是刑警寧澤鲜结,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站活逆,受9級特大地震影響精刷,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蔗候,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一怒允、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧锈遥,春花似錦纫事、人聲如沸勘畔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽炫七。三九已至,卻和暖如春钾唬,著一層夾襖步出監(jiān)牢的瞬間万哪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工抡秆, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留壤圃,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓琅轧,卻偏偏與公主長得像伍绳,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子乍桂,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,577評論 2 353

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

  • 許多集成的步驟個推官網(wǎng)都有了冲杀,這里只寫關(guān)于推送的遠(yuǎn)程推送和本地通知的步驟和代碼。APP在后臺時:走蘋果的APNS通...
    AllureJM閱讀 2,717評論 1 9
  • 寫作原因:網(wǎng)上看了很多推送文章都沒有完美的解答我的疑惑睹酌;主要有以下兩點权谁,1:推送來了我點擊應(yīng)用圖標(biāo)進(jìn)入應(yīng)用怎么取到...
    Thebloodelves閱讀 4,508評論 26 71
  • 極光推送: 1.JPush當(dāng)前版本是1.8.2,其SDK的開發(fā)除了正常的功能完善和擴(kuò)展外也緊隨蘋果官方的步伐憋沿,SD...
    Isspace閱讀 6,719評論 10 16
  • 應(yīng)用程序必須進(jìn)行適當(dāng)配置旺芽,才可以接受本地或遠(yuǎn)程通知。配置過程在iOS和OS X略有不同辐啄,但基本原理是相同的采章。在啟動...
    shenzhenboy閱讀 1,385評論 1 2
  • 他們都是萬里挑一的人悯舟,你如果足夠幸運,你會遇見他們砸民。他們的特點就是一直在努力抵怎,夢想聽起來不切實際,過得日子比你差...
    初夏的解憂雜貨鋪閱讀 372評論 0 2