NSUserDefaults未在Apple Watch上更新

时间:2016-01-20 17:08:55

标签: ios nsuserdefaults watchkit

我已经为我的iphone目标和Apple Watch目标添加了一个组:

enter image description here

在我的AppDelegate中,我有这段代码:

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    let userDefaults = NSUserDefaults(suiteName: "group.tripicons")
    userDefaults!.setObject("English", forKey: "languageOfCurrentCountry")
    userDefaults!.setObject("English", forKey: "languageOfDevice")
    userDefaults!.synchronize()
    return true
  }

然而,当它在我的方法中说nil时:

class LanguageManager: NSObject {

  ...
  let userDefaults = NSUserDefaults(suiteName: "group.tripicons")

  func watchTranslation(word: String) -> String {
    print(userDefaults?.dictionaryRepresentation())

    // BREAKS HERE
    let language = userDefaults?.objectForKey("languageOfCurrentCountry") as! String // <---- BREAKS HERE
    ...
  }
}

print语句打印的对象没有我正在寻找的密钥:

Optional(["MSVLoggingMasterSwitchEnabledKey": 0, "AppleKeyboardsExpanded": 1, "AppleLanguages": (
    en
), "AppleLanguagesDidMigrate": 2.1, "NSInterfaceStyle": macintosh, "NSLanguages": (
    en
), "AppleKeyboards": (
    "en_US@hw=US;sw=QWERTY",
    "emoji@sw=Emoji",
    "en_US@hw=US;sw=QWERTY"
)])

即使我打开苹果手表应用程序之前打开iPhone应用程序也是如此。我错过了什么吗?

== UPDATE ==

from AppDelegate:
["languageOfCurrentCountry": English, "AppleKeyboards": (
    "en_US@hw=US;sw=QWERTY",
    "emoji@sw=Emoji",
    "en_US@hw=US;sw=QWERTY"
), "AppleKeyboardsExpanded": 1, "AddingEmojiKeybordHandled": 1, "AppleLanguages": (
    "en-US"
), "ApplePasscodeKeyboards": (
    "en_US@hw=US;sw=QWERTY",
    "emoji@sw=Emoji",
    "en_US@hw=US;sw=QWERTY"
), "AppleLocale": en_US, "NSInterfaceStyle": macintosh, "MSVLoggingMasterSwitchEnabledKey": 0, "NSLanguages": (
    "en-US",
    en
), "AppleITunesStoreItemKinds": (
    audiobook,
    "tv-episode",
    booklet,
    software,
    "software-update",
    "itunes-u",
    ringtone,
    "tv-season",
    movie,
    mix,
    wemix,
    song,
    tone,
    artist,
    "podcast-episode",
    podcast,
    eBook,
    document,
    album,
    "music-video"
), "AppleLanguagesDidMigrate": 9.2, "languageOfDevice": English]

1 个答案:

答案 0 :(得分:3)

iPhone和Apple Watch之间使用NSUserDefaults进行的数据交换仅适用于watchOS 1。

如果您正在为watchOS 2开发,则应使用WatchConnectivity框架。请参阅Apple的文档here