我想测试iCloud键值存储。这是我采取的步骤:
1)购买约$ 100的苹果开发者帐户,等待其激活
2)在开发人员区域,我创建了一个App ID,一个iCloud容器,一个配置文件(iOS开发),并确保它知道我的个人设备。
3)在XCode中创建了一个新的单视图swift应用
4)在application: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
。从documentation:
在内存和磁盘之间的同步期间,此方法使用先前从iCloud接收到的更改来更新内存中的键和值集
由于您正在写入内存,然后立即调用synchronize
,因此内存中的值将被缓存的值覆盖,对于全新的应用程序,这些值将为空。系统尚未有机会使用您刚刚写入的值来更新缓存。
您应该在synchronize
中包含对applicationWillEnterForeground
的调用:
唯一建议的时间是在应用启动时或返回到前台时,以确保内存中的键值存储表示是最新的。
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()
}
关于ios - 基本的iCloud键值存储测试失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37636277/