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

后端 未结 2 903
离开以前
离开以前 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")
    }
    
    0 讨论(0)
  • 2021-01-06 03:01

    if you suffer this problem when you try to save data to extension APP by using userDefault,maybe you had written this code : [[NSUserDefaults standardUserDefaults] initWithSuiteName:@"group.xxx.com"];,this code reset default userDefault. Actually,the correct code is : [[NSUserDefaults alloc] initWithSuiteName:@"group.xxx.com"]; enter link description here

    0 讨论(0)
提交回复
热议问题