Sharing data between an iOS 8 share extension and main app

后端 未结 8 492
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 20:08

Recently, I\'ve been making a simple iOS 8 share extension to understand how the system works. As Apple states in its App Extension Programming Guide:

<
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 20:48

    Here is how I did it:

    1. Open your main app target > Capabilities > App Groups set to on
    2. Add a new app group and make sure it is ticked (e.g. group.com.seligmanventures.LightAlarmFree)
    3. Open your watch target (the one with Capabilities tab) > App Groups set to on
    4. Add a new app group and make sure it is ticked (e.g. group.com.seligmanventures.LightAlarmFree - but must be the same name as group above)
    5. Save data to the group as follows:

      var defaults = NSUserDefaults(suiteName: "group.com.seligmanventures.LightAlarmFree")
      defaults?.setObject("It worked!", forKey: "alarmTime")
      defaults?.synchronize()
      
    6. Retrieve data from the group as follows:

      var defaults = NSUserDefaults(suiteName: "group.com.seligmanventures.LightAlarmFree") 
      defaults?.synchronize()
      
      // Check for null value before setting
      if let restoredValue = defaults!.stringForKey("alarmTime") {
          myLabel.setText(restoredValue)
      }
      else {
          myLabel.setText("Cannot find value")
      }
      

提交回复
热议问题