Kodr.F
Kodr.F

Reputation: 14390

Xcode Swift appleWatch read application UserDefaults?

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 ?

Upvotes: 1

Views: 1117

Answers (2)

swiftyboi
swiftyboi

Reputation: 3221

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.

Upvotes: 1

user6426085
user6426085

Reputation:

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

Upvotes: 3

Related Questions