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



是否可以通过Watchkit扩展了解iOS应用程序是否在前台运行?

苹果建议在iPhone和手表之间共享信息的方法是通过应用程序组使用共享对象:Apple watch编程指南,请参阅"与包含iOS的应用程序共享数据"一章

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

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

最新更新