watchkitapple-watchios8.2

Get the state of the iOS app from the watchkit extension


Is it possible to know the wether the iOS app is running in foreground from the Watchkit extension?


Solution

  • Apple's recommended way to share information between the iPhone and the watch is to use a shared object via an application group: Apple Watch Programming Guide, see the chapter "Sharing Data with Your Containing iOS App".

    So after setting up a shared app group you can use AppDelegate's applicationDidEnterBackground and applicationWillEnterForeground (or similar methods that fit your needs) to write information in that shared object wich can be read by the watchkit extension:

    AppDelegate

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
        // Shared object
        let sharedDefaults = NSUserDefaults(suiteName: "group.com.example.myApp")
    
        sharedDefaults.setBool(false, forKey: "foreground")
        sharedDefaults.synchronize()
    }
    
    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    
        // Shared object
        let sharedDefaults = NSUserDefaults(suiteName: "group.com.example.myApp")
    
        sharedDefaults.setBool(true, forKey: "foreground")
        sharedDefaults.synchronize()
    }
    

    Watchkit Extension

    ...somewhere where you need the information...

    class MainInterfaceController: WKInterfaceController {    
    
        override init() {
            // Initialize variables here.
            super.init()
        }
    
    
        override func willActivate() {
            // This method is called when watch view controller is about to be visible to user
            super.willActivate()
    
            let sharedDefaults = NSUserDefaults(suiteName: "group.com.example.myApp")!
    
            let isForeground = sharedDefaults.boolForKey("foreground")
            ...
    
        }
    
        override func didDeactivate() {
            // This method is called when watch view controller is no longer visible
            super.didDeactivate()
        }
    }