健康步数获取及存储_iOS

96
Eric__li
2017.07.13 18:13* 字数 79

原本写这个demo的用途是方便完成 某个app的步数规定, 但写完后最终发现, 并无用途,
该app是通过bundleIdentifier 来区分步数来源,只能获取 iphone 或 appleWatch 的步数
也就是职能获取bundleIdentifier = com.apple.***的步数

代码奉上

import HealthKit

class ViewController: UIViewController{
    
    //获取  或  存储 健康步数 (心跳等数据同理)
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        healthKit { (succ) in
            if succ {
                //读取步数(读取当前手机中的步数)
                self.readDataFromService()
                //存储步数(存储步数到手机)
//                self.saveDataToDevice()
            }
        }
    }
    
    //设备是否支持 允许获取步数
    var healthStore: HKHealthStore?
    func healthKit(succ: @escaping (Bool) -> Void) {
        if (!HKHealthStore.isHealthDataAvailable()) {
            print("不支持")
            return
        } else {
            healthStore = HKHealthStore();
            let readDataTypes = dataTypeStep()
            healthStore?.requestAuthorization(toShare: dataTypeStep(), read: readDataTypes, completion: { (success, error) in
                succ(success)
            })
        }
    }
    
    //获取类型 (步数)
    func dataTypeStep() -> Set<HKQuantityType> {
        let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount);
        var set = Set<HKQuantityType>()
        set.insert(stepCountType!)
        return set
    }

    //读取步数
    func readDataFromService() {
        let calendar = NSCalendar.current
        let now = Date();
        var components = calendar.dateComponents(Set(arrayLiteral: .year, .month, .day, .hour, .minute, .second), from: now)
        let hour: Int = components.hour!;
        let minute: Int = components.minute!;
        let second: Int = components.second!;

        //读取某个时间段内的步数
        let s = Date(timeIntervalSinceNow: -(Double(hour * 3600 + minute * 60 + second)))
        let e = Date(timeIntervalSinceNow: -(Double(hour * 3600 + minute * 60 + second)) + 86400)
        
        let pre = HKQuery.predicateForSamples(withStart: s, end: e, options: [.strictStartDate])
        
        let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount);
        
        //以下两种方法均可以获取到所需时间段的步数
//        let sampleQuery = HKSampleQuery(sampleType: stepCountType!, predicate: pre, limit: HKObjectQueryNoLimit, sortDescriptors: [sort, end]) { (query, results, error) in
//            print("---------")
//        }
        let query = HKSourceQuery.init(sampleType: stepCountType!, samplePredicate: pre) { (query, sourse, error) in
            
        }
        healthStore?.execute(query)
    }
    
    //写入步数
    func saveDataToDevice() {
        //设置时间段, 将步数存储到设置的时间范围内
        let tmp = Date();
        let end = Date(timeInterval: -3000, since: tmp)
        let start = Date(timeInterval: -5000, since: tmp)

        let step = HKObjectType.quantityType(forIdentifier: .stepCount)
        let quant = HKQuantity(unit: HKUnit.count(), doubleValue: Double(1000))
        //device信息可以自定义,这里模仿 Apple Watch
        //原本写这个demo的用途是方便完成 某个app的步数规定, 但写完后最终发现, 并无用途,
        //该app是通过bundleIdentifier 来区分步数来源,只能获取 iphone  或 appleWatch 的步数
        //也就是职能获取bundleIdentifier = com.apple.***的步数
        let device = HKDevice.init(name: "Apple Watch", manufacturer: "Apple", model: "Watch", hardwareVersion: "Watch2,3", firmwareVersion: nil, softwareVersion: "3.2.2", localIdentifier: nil, udiDeviceIdentifier: nil)
        let obj = HKQuantitySample.init(type: step!, quantity: quant, start: start, end: end, device: device, metadata: nil)
        healthStore?.save(obj, withCompletion: { (success, error) in
            //存储完成回调
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
iOS
Web note ad 1