前提・実現したいこと
HealthKit HKStatisticsCollectionQuery を使って
collectionViewCellに歩数を毎日分表示したい
発生している問題・エラーメッセージ
一通りHealthKitの設定をし
cellに現在の日にちまでのデータを取得したいのですがなかなかうまくいかず困ってます
エラーメッセージ
該当のソースコード
import UIKit import HealthKit class ViewController: UIViewController { let myHealthKitStore = HKHealthStore() @IBAction func ninsyou(_ sender: Any) { requestAuthorization() } @IBOutlet weak var collectionView: UICollectionView! struct HealthData { var date: Date var step: Int var distance: Int init(_ date: Date, _ step: Int, _ distance: Int) { self.date = date self.step = step self.distance = distance } } func requestAuthorization() { /*(toShare typesToShare: Set<HKSampleType>?, read typesToRead: Set<HKObjectType>?, completion: @escaping (Bool, Error?) -> Void)*/ // 読み込みを許可する型. 誕生日と性別・血液型を読み込み、体重と体温を書き込めるようにしたい認証 let typeOfRead = Set(arrayLiteral: // HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)!,//誕生日 // HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.biologicalSex)!,//性別 // HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.bloodType)!,//血液型 HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,//歩数 HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!//歩行または走行距離 ) // 書き込みを許可する型. let typeOfWrite = Set(arrayLiteral: // HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)!,//体重 // HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyTemperature)!,//体温 HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,//歩数 HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!//歩行または走行距離 ) // HealthStoreへのアクセス承認をおこなう. myHealthKitStore.requestAuthorization(toShare: typeOfWrite, read: typeOfRead, completion: { (success, error) in if let e = error { print("Error: (e.localizedDescription)") return } print(success ? "success" : " Failure!") }) } var dataSource: [HealthData] = [] override func viewDidLoad() { super.viewDidLoad() //cellのxibの読み込み collectionView.dataSource = self let nib = UINib(nibName: "CollectionViewCell", bundle: nil) self.collectionView.register(nib, forCellWithReuseIdentifier: "cell") } func requestStatisticsCollection(){ let calender = Calendar.current let day = -7 let now = NSDate() let today = calender.startOfDay(for: now as Date) let endDate = now let startDate = calender.date(byAdding: Calendar.Component.day, value: day, to: today) let anchorDate = today var interval = DateComponents() interval.hour = 1 let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate as Date, options: []) let quantityType = HKSampleType.quantityType(forIdentifier: .stepCount)! let statsOptions: HKStatisticsOptions = [HKStatisticsOptions.separateBySource,HKStatisticsOptions.cumulativeSum] let query = HKStatisticsCollectionQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: statsOptions, anchorDate: anchorDate, intervalComponents: interval ) print("(String(describing: startDate))) - (endDate)") print("anchorDate: (anchorDate)") query.initialResultsHandler = { (query, results, error) in if let result = results { DispatchQueue.main.async { self.dataSource = [] for item in result.statistics() { let data = HealthData(item.startDate, Int(item.sumQuantity()!.doubleValue(for: HKUnit.count())), 0) print("(item.startDate) - (item.endDate) (item.sumQuantity()!.doubleValue(for: HKUnit.count()))") self.dataSource.append(data) } self.collectionView.reloadData() } } self.myHealthKitStore.execute(query) } } } // cellの設定 extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let data = self.dataSource[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell let formatter: DateFormatter = DateFormatter() formatter.locale = NSLocale(localeIdentifier: NSLocale.Key.languageCode.rawValue) as Locale? formatter.dateStyle = .full formatter.doesRelativeDateFormatting = true formatter.locale = Locale(identifier: "ja_JP") cell.label.text = formatter.string(from: data.date ) cell.hosuu.text = "(data.step)" // cell.kyori.text = "(String(describing: Data.distance))" return cell } }
試したこと
データの橋渡しがうまくいっていないのか
cellの自動生成までビルドできません
補足情報(FW/ツールのバージョンなど)
どなたかお力をいただければと思います
あなたの回答
tips
プレビュー