Swift でデバイストークンを取得する

iOS8 より記述方法が変わったため、iOS8 未満も対応する場合には振り分けが必要です。

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

        // iOS8 向け
        if application.respondsToSelector("registerUserNotificationSettings:") {

            let types:UIUserNotificationType = (.Alert | .Badge | .Sound)
            let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)

            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()

        } else {
            // iOS7 未満
            application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
        }

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){


        // <>と" "(空白)を取る
        let characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )

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


        println(deviceTokenString)

    }

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

        println("Couldn't register: \(error)")
    }