LoginSignup
5
5

More than 5 years have passed since last update.

Swift2.0でdeviceTokenをNSUserDefaultsに保存

Last updated at Posted at 2015-10-09

概要

NSUserDefalutsにdeviceTokenをStringで保存して、
どこかで呼び出し、という処理をやったのですが、
キャストまわりではまったので書いたコードのメモをしておきます。

  1. NSDataをNSStringで受け取るにはdescriptionを参照する点
  2. swiftはas!を使うとキャストできる、

といった2点がよくわかっていなくてはまりました。

swiftまだまだ勉強中です。

実装

以下追加します。

AppDelete.swift
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // for APNs
        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()

        // Override point for customization after application launch.
        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let ud = NSUserDefaults.standardUserDefaults()
        ud.setValue(deviceToken.description, forKey: "token")
        ud.synchronize()
    }

使いたいところで以下を呼び出し

let token:String = ud.objectForKey("token") as! String;

そもそもNSUserDefalutsに保存するがよいかどうかはあるのですが、
経験が浅いためわからないです。
やりたいことはサーバにdeviceTokenを送りたい、というシンプルなことです。

Application直下に保存しておくのがよいのかな??

参考

swiftはキャストとかが直感的になりました。
まだ馴染みがないのですが馴れるとすごくよいと思います。

swfitのcastまわりの公式ドキュメント

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5