Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

ios - Passing data to Apple Watch app

I am trying to pass data from my app into my Apple Watch app. Basically, I am using the same method as I used for creating the today widget and so I am passing data through NSUserDefaults.

The problem is, that when I run my app, the data does not update the labels in the Watch app as I would expect it to.

Here is what I have...

override init(context: AnyObject?) {
    // Initialize variables here.
    super.init(context: context)

    // Configure interface objects here.
    NSLog("%@ init", self)

    var defaults = NSUserDefaults(suiteName: "group.AffordIt")
    var totalBudgetCalculation = ""
    if (defaults!.stringForKey("totalBudgetWidget") != nil) {
            println("Worked")
        totalBudgetCalculation = defaults!.stringForKey("totalBudgetWidget")!
        initialBudgetLabel.setText("Initial: (totalBudgetCalculation)")
    }

    var currentBudgetCalculation = ""
    if (defaults!.stringForKey("currentBudgetWidget") != nil) {
        currentBudgetCalculation = defaults!.stringForKey("currentBudgetWidget")!
        currentBudgetLabel.setText("Current: (currentBudgetCalculation)")
    }
}

I tried putting this code in willActivate(), however that doesn't seem to make a difference.

Anyone know where I am going wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This applies to OS 1 only. See below for better answers.

I got it working using your method. I guess there's a couple of things you can check:

1) Are you synchronising the defaults after you set the value:

defaults?.synchronize();
NSLog("%@ ", defaults?.dictionaryRepresentation())

2) Have you enabled the App Group in both your app and your extension?

App Group capability for App Target App Group capability for Watch Extension Target

3) Are you using the correctly named app group when constructing the NSDefaults? For example, I use:

NSUserDefaults(suiteName: "group.com.brindysoft.MyWatch");

Once all that's set up I run the app, set the value in the defaults, then run the glance target which reads the value from the default and that seems to work!

enter image description here

  1. Still stuck? check your app groups in your apple account

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...