0

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

4

2 回答 2

0

Apple 推荐的在 iPhone 和手表之间共享信息的方法是通过应用程序组使用共享对象:Apple Watch 编程指南,请参阅“与包含的 iOS 应用程序共享数据”一章。

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

应用委托

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()
    }
}
于 2015-04-05T07:17:41.567 回答
0

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

   class func openParentApplication(_ userInfo: [NSObject : AnyObject],
                               reply reply: (([NSObject : AnyObject],
                                              NSError?) -> Void)?) -> Bool
于 2015-08-18T11:14:33.510 回答