我想测试iCloud键值存储。以下是我采取的步骤:
1)以100美元左右的价格购买苹果开发者帐户,等待其激活
2) 在开发者区,我创建了一个应用程序 ID、一个 iCloud 容器、一个配置文件(iOS 开发),并确保它知道我的个人设备。
3)在XCode中创建了一个新的单视图swift应用程序
4)在应用程序中添加了以下代码:didFinishLaunchingWithOptions:方法:
let keyStore = NSUbiquitousKeyValueStore.defaultStore()
#if (arch(i386) || arch(x86_64)) && os(iOS)
//let DEVICE_IS_SIMULATOR = true
keyStore.setString("testValue2", forKey: "testKey2")
let didSync = keyStore.synchronize()
print("synched: (didSync)")
#else
//let DEVICE_IS_SIMULATOR = false
let didSync = keyStore.synchronize()
print("synched: (didSync)")
if let theString = keyStore.stringForKey("testKey2") {
print("the string: (theString)")
}
else {
print("did not find string with specified key")
}
#endif
5) 在 5s 模拟器上启动应用程序,确认 keyStore.synchronize() 返回 true。
6) 等待 10 秒
7)在我的iPhone 6+上启动了该应用程序,确认keyStore.synchronize()返回true。
8)可悲的是,它打印出"没有找到带有指定键的字符串"
我做错了什么?
您不应该调用synchronize
。 从文档中:
在内存和磁盘之间同步期间,此方法会使用以前从 iCloud 收到的更改更新内存中的键和值集
由于您正在写入内存,然后立即调用synchronize
,因此您的内存中值将被缓存的值覆盖,在全新应用程序的情况下,缓存值为空。 系统尚未有机会使用您刚刚写入的值更新缓存。
您应该在applicationWillEnterForeground
中包含对synchronize
的调用:
唯一建议调用此方法的时间是在应用启动时或返回到前台时,以确保内存中的键值存储表示形式是最新的。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let keyStore = NSUbiquitousKeyValueStore.defaultStore()
keyStore.synchronize()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.iCloudChangedNotification(_:)), name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification, object: nil)
keyStore.setString("testValue2", forKey: "testKey2")
if let theString = keyStore.stringForKey("testKey2") {
print("the string: (theString)")
}
else {
print("did not find string with specified key")
}
return true
}
func iCloudChangedNotification(notification: NSNotification) {
print("iCloud changed")
if let userInfo = notification.userInfo {
if let changeReason = userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] as? NSNumber {
print("Change reason = (changeReason)")
}
if let changedKeys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] {
print("ChangedKeys = (changedKeys)")
}
}
let keyStore = NSUbiquitousKeyValueStore.defaultStore()
if let theString = keyStore.stringForKey("testKey2") {
print("the string: (theString)")
}
else {
print("did not find string with specified key")
}
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
let keyStore = NSUbiquitousKeyValueStore.defaultStore()
keyStore.synchronize()
}