0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift2 での iCloud Notification の問題

Last updated at Posted at 2015-11-24

Swiftが1.2から2になって型のチェックが更に厳しくなりました。それによって、iCloud の Notificaiton が従来のコードだとうまく動かないことがわかりました。
iCloud にKeyValueStoreでデータを保存していて、変化をNSNotification で受け取る場合、まずどこかでNotificationCenter にAddObjectでNSUbiquitousKeyValueStoreDidChangeExternallyNotification を登録します。
例えば、Viewdid Load であれば、

    override func viewDidLoad() {
        super.viewDidLoad()
        // iCloudのデータに変更があった時の通知を受け取る
        let center = NSNotificationCenter.defaultCenter()
        center.addObserver(self,
            selector: "ubiquitousDataDidChange:",
            name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification,
            object: nil)
    }

といった感じです。
そして、データ変更の処理メソッドを定義するわけですが、Swift1.2であれば、

    func ubiquitousDataDidChange(notification: NSNotification) {
        let store = NSUbiquitousKeyValueStore.defaultStore()
        // 通知オブジェクトから渡ってくるデータを取得
        if let info = notification.userInfo as? [String: [String]] {
            if let keys = info[NSUbiquitousKeyValueStoreChangedKeysKey] {
                for key in keys {
                    let num = store.doubleForKey(key)
                    self.label.text = "\(num)"
                }
            }
        }
    }

でOKでしたが、Swift2ではこれだと、info はいつも nil になります。
NSNotificationで渡されるuserInfoは、[NSObject: [AnyObject]] であり、[String: [String]] にキャストしようとすると、最初のデータは、
["NSUbiquitousKeyValueStoreChangeReasonKey" : Int32(0)]のようであり、nil となります。
Swift2の場合には、次のように実際に使うところでキャストするようにしないとうまく動作しません。

    func ubiquitousDataDidChange(notification: NSNotification) {
        let store = NSUbiquitousKeyValueStore.defaultStore()
        // 通知オブジェクトから渡ってくるデータ取得
        if let info = notification.userInfo {
            if let keysrow = info[NSUbiquitousKeyValueStoreChangedKeysKey] {
                let keys = keysrow as! [String]
                for key in keys {
                    let num = store.doubleForKey(key)
                    label.text = "\(num)"
                }
            }
        }
    }
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?