You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Apple Watch自定义SwiftUI应用优先级高于Fitness应用?

让SwiftUI锻炼计时应用在Apple Watch上保持前台的方案

要实现你的应用在放下手腕时优先级高于Fitness应用、保持前台显示,核心是利用WatchOS为锻炼类应用提供的前台保留机制,参考系统秒表的实现逻辑,具体操作如下:

1. 开启锻炼后台模式

在Xcode中打开你的Watch App target设置,进入Signing & Capabilities,添加Background Modes能力并勾选Workout processing。这一步会让系统将你的应用识别为锻炼相关应用,获得更高的前台优先级。

2. 启动极简WKWorkoutSession

系统秒表能保持前台的关键在于启动了锻炼会话,你可以创建一个极简的WKWorkoutSession——不需要完整的健康数据追踪,仅用来告知系统你的应用处于活跃锻炼状态:

import WatchKit
import HealthKit

class WorkoutSessionManager: NSObject, WKWorkoutSessionDelegate {
    private var workoutSession: WKWorkoutSession?
    private let healthStore = HKHealthStore()
    
    func startSession() {
        guard HKHealthStore.isHealthDataAvailable() else { return }
        
        let config = WKWorkoutConfiguration()
        config.activityType = .other // 根据你的应用场景选择合适的活动类型
        config.locationType = .indoor
        
        workoutSession = WKWorkoutSession(healthStore: healthStore, configuration: config)
        workoutSession?.delegate = self
        workoutSession?.start()
    }
    
    func endSession() {
        workoutSession?.end()
        workoutSession = nil
    }
    
    // 实现必填的代理方法
    func workoutSession(_ workoutSession: WKWorkoutSession, didChangeTo toState: WKWorkoutSessionState, from fromState: WKWorkoutSessionState, date: Date) {}
    func workoutSession(_ workoutSession: WKWorkoutSession, didFailWithError error: Error) {}
}

在你的SwiftUI视图中,启动计时时调用startSession(),停止计时时调用endSession()即可。

3. 配置HealthKit权限

启动WKWorkoutSession需要向用户申请HealthKit权限,在Watch App的Info.plist中添加以下两个键值对:

  • NSHealthShareUsageDescription:说明你需要分享健康数据的原因(比如"用于维持锻炼计时的前台状态")
  • NSHealthUpdateUsageDescription:说明你需要更新健康数据的原因

4. 额外的前台保持技巧

如果上述方法稳定性不足,可以在计时开始时调用以下代码强制保持前台:

import WatchKit

func keepAppFrontmost() {
    WKExtension.shared().isFrontmost = true
    // 调度后台刷新,防止系统挂起应用
    WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: Date().addingTimeInterval(60), userInfo: nil) { error in
        if let error = error {
            print("Background refresh failed: \(error.localizedDescription)")
        }
    }
}

注意事项

  • 不要在非计时状态下保持锻炼会话,否则会额外消耗电量,也不符合WatchOS的应用规范。
  • 测试时需确保Fitness应用处于锻炼状态,再切换到你的应用放下手腕验证效果。

内容的提问来源于stack exchange,提问作者Jonathan Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:31:09