如何删除重量结果中产生的文字?

时间:2018-10-12 12:25:47

标签: ios swift health-kit

我设法调用HealthKit来获取最新的体重数据。但是,当我运行它时,它包含如下全部文本:

64 kg E457AF14-36D7-4547-AFAA-EF23DDD6642D "Health" (12.0), "iPhone10,4" (12.0)metadata: {
    HKWasUserEntered = 1;
} (2018-10-12 13:12:00 +0100 - 2018-10-12 13:12:00 +0100)

这是我的代码:

    func getTodaysWeight(completion: @escaping (HKQuantitySample) -> Void) {

    guard let weightSampleType = HKSampleType.quantityType(forIdentifier: .bodyMass) else {
        print("Body Mass Sample Type is no longer available in HealthKit")
        return
    }

    //1. Use HKQuery to load the most recent samples.
    let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast,
                                                          end: Date(),
                                                          options: [])
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate,
                                          ascending: false)
    let limit = 1
    let sampleQuery = HKSampleQuery(sampleType: weightSampleType,
                                    predicate: mostRecentPredicate,
                                    limit: limit,
                                    sortDescriptors: [sortDescriptor]) { (query, samples, error) in


                                        //2. Always dispatch to the main thread when complete.
                                        DispatchQueue.main.async {
                                            guard let samples = samples,
                                                let mostRecentSample = samples.first as? HKQuantitySample else {
                                                    print("getUserBodyMass sample is missing")
                                                    return
                                            }
                                            completion(mostRecentSample)
                                        }
    }
    HealthStore.execute(sampleQuery)
}



////////////////////////////////////


private func updateWeightCountLabel() {
    getTodaysWeight { (result) in
        print("\(result)")
        DispatchQueue.main.async {
            self.totalWeight.text = "\(result)"
            self.totalWeight.text = String(format:"%.2f")
            print("\(result)")
        }
    }
}

我首先尝试了截断结尾。显然,所有这些文本仍在那儿,但是它很混乱并且不是真正可以接受的。

然后,我尝试将以下代码添加到私有功能下方,就像我在另一个ViewController中将其设置为两位小数一样。但是,在下面使用此代码只会导致UIlabel字符串中未显示任何结果。

self.totalWeight.text = String(format:"%.2f")
            print("\(result)")

这是我进行任何编程的第一次尝试,因此我将第一个应用程序个人用作正在进行的学习过程,并在进行过程中逐渐添加,更改,破坏。

2 个答案:

答案 0 :(得分:2)

您正在打印来自完成处理程序HKQuantitySample的结果。该对象包含多个属性,因此打印整个内容将为您提供当前所看到的输出以及有关该对象的所有信息。尝试仅打印result.quantity进行测量。看看Apple的this页面中有关该类型的内容。

答案 1 :(得分:0)

一个简短的建议。

您可以使用字符串offsetBy

 let weight_1 = weight.substring(to:weight.index(weight.startIndex, offsetBy: 6)) // weight is the complex output you got 
 print(weight_1)

此打印:

 64 kg

即使人是120公斤也应该可以工作