从 watchkit 扩展中获取 iOS 应用程序的状态

Get the state of the iOS app from the watchkit extension

是否可以从 Watchkit 扩展中知道 iOS 应用是否 运行 在前台?

Apple 推荐的在 iPhone 和手表之间共享信息的方法是通过应用程序组使用共享对象:Apple Watch Programming Guide,请参阅章节 "Sharing Data with Your Containing iOS App".

因此,在设置共享应用程序组后,您可以使用 AppDelegate 的 applicationDidEnterBackgroundapplicationWillEnterForeground(或适合您需要的类似方法)在该共享对象中写入信息,该对象可以读取手表套件扩展:

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 扩展

...在您需要信息的地方...

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()
    }
}

如您所知,此函数将 watchKit 应用程序请求发送到 iOS 应用程序,并且 handleWatchKitExtensionRequest iOS 应用程序将捕获此请求。所以下面的函数有 reply 负责处理您与信息或数据的连接。因此,在 appDelegate 中,您应该为 reply 提供任何值,然后在 watchKit 控制器中检查此值。

   class func openParentApplication(_ userInfo: [NSObject : AnyObject],
                               reply reply: (([NSObject : AnyObject],
                                              NSError?) -> Void)?) -> Bool