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

时间:2015-04-05 05:21:21

标签: watchkit apple-watch ios8.2

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

2 个答案:

答案 0 :(得分:0)

Apple建议在iPhone和手表之间共享信息的方法是通过应用程序组使用共享对象:Apple Watch Programming Guide,请参阅“与包含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 Extension

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

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

答案 1 :(得分:0)

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

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