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

如何判断Apple Watch是否已连接Apple Health Kit?

判断Apple Watch是否连接Apple Health Kit的方法

Health Kit本身没有提供直接检测Apple Watch实时连接状态的API,但可以通过两种间接方式来判断:

  • 检查已授权的数据源列表
    你可以查询Health中已授权的数据源,判断是否存在Apple Watch设备:

    import HealthKit
    
    func hasAppleWatchAsHealthSource() -> Bool {
        guard HKHealthStore.isHealthDataAvailable() else { return false }
        let healthStore = HKHealthStore()
        // 选择一个你已申请权限的健康数据类型(比如步数)
        guard let stepType = HKObjectType.quantityType(forIdentifier: .stepCount) else { return false }
        
        let authorizedSources = healthStore.sources(for: stepType)
        for source in authorizedSources {
            if source.productType == HKProductTypeAppleWatch {
                return true
            }
        }
        return false
    }
    

    注意:这个方法只能说明Apple Watch曾经连接并同步过Health数据,若用户解除配对后未移除数据源,仍会返回true,无法反映实时连接状态。

  • 查询来自Apple Watch的健康样本
    通过获取近期的健康数据样本,判断其来源是否为Apple Watch,以此间接推断手表是否处于活跃同步状态:

    func checkRecentAppleWatchHealthData(completion: @escaping (Bool) -> Void) {
        guard HKHealthStore.isHealthDataAvailable() else {
            completion(false)
            return
        }
        let healthStore = HKHealthStore()
        guard let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate) else {
            completion(false)
            return
        }
        
        // 查询过去24小时内的心率数据
        let predicate = HKQuery.predicateForSamples(withStart: Date().addingTimeInterval(-86400), end: Date(), options: .strictStartDate)
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
        let query = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: 1, sortDescriptors: [sortDescriptor]) { _, samples, error in
            guard let sample = samples?.first as? HKQuantitySample, error == nil else {
                completion(false)
                return
            }
            let isFromWatch = sample.sourceRevision.source.productType == HKProductTypeAppleWatch
            completion(isFromWatch)
        }
        healthStore.execute(query)
    }
    

    如果能获取到近期来自Apple Watch的样本,说明手表近期同步过数据,大概率处于连接状态。

  • 额外说明

    • 以上方法都要求你已经向用户申请了对应健康数据的读写权限,否则无法获取数据源或样本信息。
    • 若需要严格的实时连接检测,可结合Core Bluetooth框架检测Apple Watch的蓝牙连接状态,但这不属于Health Kit的范畴。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 00:04:59