Posted at

【iOS8とiOS7対応】SwiftでPush

More than 3 years have passed since last update.

iOS8からPush通知の登録方法が変わりましたが、現場ではiOS7も対応しないといけないと思います。

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

var currentVersion = (UIDevice.currentDevice().systemVersion as NSString).floatValue
if currentVersion >= 8.0{
var types:UIUserNotificationType = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: types, categories: nil )
application.registerUserNotificationSettings( settings )
application.registerForRemoteNotifications()
}else{
var types:UIRemoteNotificationType = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
application.registerForRemoteNotificationTypes(types)
}

return true
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
application.registerForRemoteNotifications()
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )

var deviceTokenString: String = ( deviceToken.description as NSString )
.stringByTrimmingCharactersInSet( characterSet )
.stringByReplacingOccurrencesOfString( " ", withString: "" ) as String

println( deviceTokenString )
}

func application( application: UIApplication!, didFailToRegisterForRemoteNotificationsWithError error: NSError! ) {

println( error.localizedDescription )
}

サンプルコードを載せておきます。