问题
i am writing a small universal game for iOS. the highscore will be synched accross devices through an iCloud Key/Value store.
getting the newest score:
func retrieveHighestScore() -> Int64 {
let iCloudScore: Int64 = NSUbiquitousKeyValueStore.defaultStore().longLongForKey(KeyValueKeyClassification.KeyHighscore.toRaw())
let localScore: Int64 = Int64(NSUserDefaults.standardUserDefaults().integerForKey(KeyValueKeyClassification.KeyHighscore.toRaw()))
var result: Int64 = 0
if localScore > iCloudScore {
storeNewHighscore(localScore)
result = localScore
} else {
storeNewHighscore(iCloudScore)
result = iCloudScore
}
return result
}
storing a new highscore
func storeNewHighscore(newScore: Int64) {
NSUbiquitousKeyValueStore.defaultStore().setLongLong(newScore, forKey: KeyValueKeyClassification.KeyHighscore.toRaw())
NSUserDefaults.standardUserDefaults().setInteger(Int(newScore), forKey: KeyValueKeyClassification.KeyHighscore.toRaw())
if NSUbiquitousKeyValueStore.defaultStore().synchronize() {
println("Synched Successfully")
}
}
for some reason however the scores are not synched.
- no errors
- no crashes
- no null values
i always get the highest score from the current device, never the one achieved on others.
could the reason be within itunesconnect or is something wrong with my code? i am using an ipad and an iphone for testing, both logged in to my own icloud account.
i am registering for the changes like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "icloudKeyValueChanged", name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification, object: nil)
if NSUbiquitousKeyValueStore.defaultStore().synchronize() {
println("initial Synched Successfully")
}
return true
}
but the function 'icloudKeyValueChanged' is never called.
iCloud Capabilities all are ok as it seems:
回答1:
I had the same problem. Logging of iCloud on my device, and logging back in, solved the problem :-)
回答2:
Its probably just simply adding the synchronize to your highscore storer:
func storeNewHighscore(newScore: Int64) {
NSUbiquitousKeyValueStore.defaultStore().setLongLong(newScore, forKey: KeyValueKeyClassification.KeyHighscore.toRaw())
NSUserDefaults.standardUserDefaults().setInteger(Int(newScore), forKey: KeyValueKeyClassification.KeyHighscore.toRaw())
NSUserDefaults.standardUserDefaults().synchronize()
if NSUbiquitousKeyValueStore.defaultStore().synchronize() {
println("Synched Successfully")
}
}
来源:https://stackoverflow.com/questions/26572855/icloud-key-value-store-synchronization-issues-nsubiquitouskeyvaluestoredidchang