在iOS8之後的遠程推送寫法

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later   


IOS8 PUSH解決方法


昨天晚上整理PUSH的東西,準備些一個教程,全部弄好之後,發現沒有達到預期的效果,本以爲是服務器代碼的問題(因爲本人對PHP代碼一點都不懂),所以在網上四處搜索,後來看xcode log才發現,原來是IOS8系統更新了的問題,提示 registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later.


使用IOS8 xcode6的同學,在使用推送(push)的時候應該已經出現這個問題了。那麼讓我們來看看具體的解決方法。


iOS 8 has changed notification registration in a non-backwards compatible way. While you need to support iOS 7 and 8 (and while apps built with the 8 SDK aren't accepted), you can check for the selectors you need and conditionally call them correctly for the running version.


Here's a category on UIApplication that will hide this logic behind a clean interface for you that will work in both Xcode 5 and Xcode 6.


// IOS8 新系統需要使用新的代碼咯
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)];
}


原本在IOS7當中 判斷PUSH是否打開的方法是:
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
return (types & UIRemoteNotificationTypeAlert);


如果將這段代碼使用在 IOS當中,雖然不會出現crash的現象,但是基本沒什麼作用。
在IOS8中,我們使用如下的新代碼來取代以上的代碼


{
UIRemoteNotificationType types;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
   {
 types = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
    }
else
   {
 types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
    }


return (types & UIRemoteNotificationTypeAlert);
}
發佈了69 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章