簡體   English   中英

如何使用 Swift 中的 Codable 將多個數據保存到本地 json 文件中

[英]How to save multiple data into local json file with Codable in Swift

我正在做 iWatch 應用程序,我正在跟蹤 4 分鍾步行,以獲取每秒心率多個數據。

我正在獲取數據,我必須將其保存到本地 json 文件中。

我正在嘗試將數據添加到 Codable,但是,我只獲得了單個數據。

我是斯威夫特的新手。

以下是必填格式。

{   "items" : [
    {
      "endDate" : "2019-12-11",
      "HeartRate" : "82 BPM",
      "startDate" : "2019-12-11"
    },
    {
      "endDate" : "2019-12-11",
      "HeartRate" : "79 BPM",
      "startDate" : "2019-12-11"
    }   ] }

以下是我在主類中的數據。

    func workoutBuilder(_ workoutBuilder: HKLiveWorkoutBuilder, didCollectDataOf collectedTypes: Set<HKSampleType>) {
              guard let hrType = HKQuantityType.quantityType(forIdentifier: .heartRate),
              let distanceType = HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning) else {
                  return
          }
          if collectedTypes.contains(hrType) {
              if let hrQuantity = workoutBuilder.statistics(for: hrType)?.mostRecentQuantity() {
                  // We want to have BPM
                  let hrUnit = HKUnit(from: "count/min")
                  let hr = Int(hrQuantity.doubleValue(for: hrUnit))
              //    print("HR: \(hr)")
                self.bpmLabel.setText(String(hr))

                let jsonData = HealthItem.init(endDate: formattedDateFromString()!, HeartRate: String(hr), startDate: formattedDateFromString())
                print("jsonData \(jsonData)")
   }
}

結構編碼類

struct HealThInfo: Codable {
    let items: [HealthItem]?
}

struct HealthItem: Codable {
    let endDate: String?
    let HeartRate: String?
    let startDate: String?
}

但是,它只保存單個數據,而不是多個數據。

jsonData HealthItem(endDate: Optional("2020-02-04"), HeartRate: Optional("87"), startDate: Optional("2020-02-04"))

您可以使用波紋管功能

func getArrayViaCodable<T : Codable>(arrDict : [[String : Any]]) -> [T]? {
    if let jsonData = try?  JSONSerialization.data(
        withJSONObject: arrDict,
        options: .prettyPrinted
       ){
       do {
           let posts = try JSONDecoder().decode([T].self, from: jsonData)
            return posts
       } catch {
            print(error)
            return nil
       }
   } else {
        return nil
   }
}

現在使用像

if let dictresponse = responsedata as? [String: Any] {
    if let itemArray = data["items"] as? [[String: Any]] {
        let arrHealthInfo : [HealThInfo] = getArrayViaCodable(arrDict: itemArray)
    }
}

collectedTypes是類型HKSampleType的陣列。 您應該遍歷 collectTypes 以獲取所有數據。 希望對你有幫助。

您永遠不會使用 HealThInfo 對象。

let jsonData = HealthItem.init(endDate: formattedDateFromString()!, HeartRate: String(hr), startDate: formattedDateFromString())
let healtInfo = HealThInfo() // maybe load from disk with previous data?
healtInfo.items.append(jsonData)
print("jsonData \(healtInfo)")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM