使用 enableWaterLock

Use enableWaterLock

我想在我的 watchOS 应用程序中使用新的 "enableWaterLock" 功能,但我无法使用它。

这是我的代码:

@IBAction func lockScreen() {
    if #available(watchOSApplicationExtension 4.0, *) {
        WKExtension.shared().enableWaterLock()
    }
}

lockScreen() 从菜单按钮调用,如果满足该功能的所有条件,则添加到 willActivate() 函数中。

    //Screen Lock
    if #available(watchOSApplicationExtension 4.0, *) {
        if WKInterfaceDevice.current().waterResistanceRating == .wr50 {
            addMenuItem(with:.block, title: "Lock Screen", action: #selector(lockScreen))
        }
    }

文档中说:

The following rules apply when using Water Lock:

  • You can only enable Water Lock when the app is running in the foreground during an active workout or location session.
  • The app must be running on a supported device (the WKInterfaceDevice object's waterResistanceRating property must be set to wr50).
  • Water Lock remains active until the user unlocks it. You cannot programmatically unlock the watch.

所以我想我的手表应用程序没有进行活动锻炼或位置会话。 成为这两者之一需要什么? 我的应用程序使用了 locationManager,但这显然还不够。

您需要创建一个 HKWorkoutSession 对象

let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = HKWorkoutActivityType.swimming
workoutConfiguration.swimmingLocationType = HKWorkoutSwimmingLocationType.pool
workoutConfiguration.lapLength = HKQuantity(unit: .yard(), doubleValue: 25)

do {
    var workoutSession = try HKWorkoutSession(configuration: workoutConfiguration)
    workoutSession?.delegate = self         
    healthStore.start(workoutSession!)
} catch {
    // ...
}

您可以watch the Apple example from WWDC at 6:23查看Apple创建锻炼会话和启用水锁的完整示例。