watchos-4

Use enableWaterLock


I want to use the new "enableWaterLock" feature in my watchOS app, but I can't make it work.

Here's my code:

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

lockScreen() is called from a menu button, that is added in the willActivate() function, if all criteria for the feature are met.

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

In the documentation is says:

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.

So I guess my watch app is not and active workout or location session. What's needed to be one of these two? My app uses locationManager, but that's apparently not enough.


Solution

  • You need to create a HKWorkoutSession object

    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 {
        // ...
    }
    

    You can watch the Apple example from WWDC at 6:23 to see Apple's full example of creating a workout session and enabling water lock.