Just a Computer Graphics Studio & My Life

每年iOS更新後,SDK中多少會有些API在最新的版本被棄用,此時就要去寫condition code分別跑在不同版本的iOS。Notification也在iOS 8有所變動,包含Remote Notification與Local Notification,我們就來看怎麼改比較容易吧~

iOS 8 Remote:Local Notification

如果沒有處理iOS 8的情況,是不會跳出請求允許傳送通知的提示喔!

Remote Notification可以這麼寫:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // ---------------------------------------------------------------------- //
    // 向 Apple 註冊並取得 token
    // ---------------------------------------------------------------------- //

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
}

Local Notification可以這麼做:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // The following line must only run under iOS 8. This runtime check prevents
    // it from running if it doesn't exist (such as running under iOS 7 or earlier).
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
}

可以發現,Local Notification在iOS 7以前不用寫任何註冊的code,iOS 8以後才開始要寫呢!

加入處理iOS 8的Local Notification後,總算能像iOS 7以前那樣跳出提醒該丟垃圾的提示囉~

App在前景時

iOS 8 Remote:Local Notification2

App在背景時

iOS 8 Remote:Local Notification3
參考:

Advertisements

Comments on: "[iOS] iOS 8 Remote/Local Notification" (3)

  1. 您好:
    請教您,在程式未啟動狀態下,進入app如何取得推播訊息??

    謝謝

    喜歡

    • 好問題!

      Remote和Local都可以在專案中的AppDelegate.m實作已定義的方法:

      Remote:
      – (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo NS_AVAILABLE_IOS(3_0);

      Local:
      – (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification NS_AVAILABLE_IOS(4_0);

      喜歡

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: