Why doesn't NSUserDefaults work between my app & share extension?

后端 未结 2 902
离开以前
离开以前 2021-01-06 02:46

I have an iOS app with a share extension. I am trying to share data between them using NSUserDefaults and App Groups but, while I can write into the NSUD object, read it, an

2条回答
  •  醉梦人生
    2021-01-06 02:56

    Not sure if defaults.addSuite(named: ...) does the same as UserDefaults(suiteName: ...). In my app I use appGroups this way and it works as expected:

    // write
    if let userDefaults = UserDefaults(suiteName: appGroupName) {
        userDefaults.set("---" as AnyObject, forKey: "distance")
        userDefaults.set("---" as AnyObject, forKey: "altitude")
        ...
        userDefaults.synchronize()
    }
    
    // read
    if let userDefaults = UserDefaults(suiteName: appGroupName) {
        self.distanceLabel.text = userDefaults.string(forKey: "distance")
        self.altitudeLabel.text = userDefaults.string(forKey: "altitude")
    }
    

提交回复
热议问题