Sharing data between an iOS 8 share extension and main app

后端 未结 8 509
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    In my scenario I'm sharing data between the parent iOS app and WatchKit. I'm using Xcode 6.3.1, iOS Deployment Target 8.3

    var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")
    

    In your viewDidLoad make sure you synchronize:

        override func viewDidLoad() {
        super.viewDidLoad()
    
        defaults?.synchronize()
    
    }
    

    Example of a button sending text but of course you can pass whatever:

     @IBAction func btnSend(sender: UIButton) {
        var aNumber : Int = 0;
        aNumber = aNumber + 1
    
        //Pass anything with this line
        defaults?.setObject("\(aNumber)", forKey: "userKey")
        defaults?.synchronize()
    
    }
    

    Then on the other side make sure app group matches:

     var defaults = NSUserDefaults(suiteName: "group.yourappgroup.example")
    

    Then synchronize and cal: (In this case "lblNumber" is an IBOutlet label)

    defaults?.synchronize()
    var tempVar = defaults!.stringForKey("userKey")!;
    lblNumber.setText(tempVar);
    

    Then if you wanted to set something on this side and sync it back then just do the same thing and synchronize and just make sure the stringForKey that you call on the other side is the same:

    defaults?.setObject("sending sample text", forKey: "sampleKey")
    defaults?.synchronize()
    

    Hope this makes sense

提交回复
热议问题