1

i am trying to read application UserDefaults from AppleWatch extension , after 2 days of R&D failure i am posting this thread .

for example what i am trying to do is to figure out if the user logged in or not form appleWatch side using the following code ( even if app terminated ):

struct ContentView: View {

    let auth_token:String = UserDefaults(suiteName: "group.mybundle.app.com")!.string(forKey: "token") ?? ""

    @ViewBuilder
    var body: some View {

        if self.auth_token == "" {
             Text("You need to be Logged in").frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
        }else{
              WebImage(imageURL: URL(string: token)).frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center)
        }

    }
}

and from the application side once the user successfully logged in :

   UserDefaults(suiteName: "group.mybundle.app.com")!.set(rr, forKey: "token")
   UserDefaults(suiteName: "group.mybundle.app.com")!.synchronize()

i am still unable to read the token

what is the simplest way to read parent application data UserDefaults from appleWatch extension ?

Kodr.F
  • 13,932
  • 13
  • 46
  • 91

2 Answers2

3

Sharing app group from iOS app to Apple Watch seems to have been deprecated or not recommended, as discussed here.

One way to transfer data from your iOS app to WatchOS app is by using the WatchConnectivity framework. Here is Apple's official documentation.

Something to keep in mind: 1. in cases when your watch app is running in the background

  1. Also here're some sample codes

  2. A sample app from Apple

1

Like Shunzhe mentioned, you can no longer share UserDefaults between iOS and WatchOS.

You can use the sendMessage:replyHandler:errorHandler method of WatchConnectivity to wake up the iPhone, run some code, and send something back to the watch.

More info here.

swiftyboi
  • 2,965
  • 4
  • 25
  • 52
  • Yes, it should launch the iPhone app if it is terminated. The only requirement is that the isReachable property of WCSession is set to true. That happens when the iPhone is in range and the watch extension is running in the foreground or running with a high priority in the background. (Workout, complication refresh, etc.) – swiftyboi Nov 27 '19 at 15:03
  • is it possible if u have github link or any small project , explain how i can get data from the phone when the phone is terminated ? believe it or not i am still unable to do that LOL , i am so close to break my watch – Kodr.F Dec 20 '19 at 13:53