5

I want to display data from firebase realtime database in watch app. I have one method to fetch data from firebase in iOS parent App. From watch app I am sending message to iOS parent app, iOS parent app will fetch data from firebase and reply to watch app with that data.

In iOS parent App activated WCSession as below,

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    // Watch Connectivity setup
    if WCSession.isSupported() {
        let session = WCSession.default
        session.delegate = self
        session.activate()
    }

    return true
}

Same way activated session in ExtensionDelegate in Watch Extension,

ExtensionDelegate.swift

func applicationDidFinishLaunching() {
    // Perform any final initialization of your application.

    if WCSession.isSupported() {
        let session = WCSession.default
        session.delegate = self
        session.activate()
    }
}

Now in InterfaceController class sent message to iOS parent app and get data in reply.

InterfaceController.swift

override func awake(withContext context: Any?) {
    super.awake(withContext: context)
    getData()
}

func getData() {
    if WCSession.default.isReachable {
        session.sendMessage(["Request": "GetData"], replyHandler: { (dictReply) in
            print(dictReply)
        }) { (error) in
            print(error)
        }
    } else {
        let action = WKAlertAction(title: "Ok", style: .cancel) {

        }
        self.presentAlert(withTitle: "Error", message: "iPhone is not reachable, try reconnecting watch with iPhone and try again.", preferredStyle: .alert, actions: [action])
    }
}

Handled received message in iOS parent app and sent data in reply as dictionary.

AppDelegate.swift

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    guard let request = message["Request"] as? String else {
        replyHandler([:])
        return
    }

    switch request {
    case "GetData":
        // Call method to get data from firebase realtime database and send response dictionary in replyHandler for demo purpose currently passed test data
        replyHandler(["test" : "Hello..!!!"])
    default:
        replyHandler([:])
    }
}

Now first time when run in device its working fine, bt after restarting apple watch opening watch app and its giving me error in alert "iPhone is not reachable, try reconnecting watch with iPhone and try again." that means WCSession.default.isReachable returning false every time. Application stuck here and just showing black screen on Apple watch.

Also If I run app from xcode then its working every time.

I am using iPhone 8 and Apple Watch series 1

Krupa Kadecha
  • 1,056
  • 8
  • 8

0 Answers0