## はじめに
iOS アプリで歩数データを扱うとき、HealthKit は必須のフレームワークです。しかし、HealthKit の認証システムには独特の仕様があり、一般的な認証パターンとは異なる実装が必要になります。
本記事では、実際にアプリ開発で遭遇した「ヘルスケアアプリで歩数アクセスを許可しているのに、アプリでは認証拒否される」問題の原因と解決方法を詳しく解説します。
## 問題の発生状況
### 症状
- ユーザーが設定 → プライバシーとセキュリティ → ヘルスケア → アプリ名 → 歩数を「オン」に設定済み
- しかし、アプリ内では `[NOTICE] HealthKit authorization denied` のログが出力
- `requestAuthorization()` が `false` を返す
### 従来の実装(問題のあるコード)
```swift
public func requestAuthorization() async throws -> Bool {
let readTypes: Set<HKObjectType> = [
HKQuantityType.quantityType(forIdentifier: .stepCount)!,
]
try await healthStore.requestAuthorization(toShare: [], read: readTypes)
// ❌ この判定が問題
return authorizationStatus == .sharingAuthorized
}
public var isAuthorized: Bool {
// ❌ この判定も問題
return authorizationStatus == .sharingAuthorized
}
```
## HealthKit認証システムの特殊性
### 他のフレームワークとの違い
一般的なフレームワーク(例:CoreMotion)では、認証状態は分かりやすく定義されています:
```swift
// CoreMotion の場合(参考)
let status = CMMotionActivityManager.authorizationStatus()
switch status {
case .notDetermined: // 未決定
case .authorized: // 許可済み
case .denied: // 拒否済み
case .restricted: // 制限中
}
```
しかし、**HealthKit はプライバシー保護を重視**しており、以下の特徴があります:
### HealthKit の3つの認証状態
```swift
enum HKAuthorizationStatus {
case notDetermined // 未決定
case sharingAuthorized // 許可済み
case sharingDenied // 拒否済み
}
```
### 重要な仕様
1. **プライバシー保護のため、拒否状態を隠すことがある**
2. **認証状態と実際のデータアクセス可否は別物**
3. **実際のクエリを実行するまで、真のアクセス権限が分からない**
## 問題の根本原因
参考:[potatotips でHealthKitの権限に苦労した話を発表しました - dely Tech Blog](https://tech.dely.jp/entry/potatetips_86)
この問題の根本原因は、**認証状態の判定ロジックが HealthKit の仕様に適していない**ことでした:
### 問題1: 認証判定が厳格すぎる
```swift
// ❌ 問題のある判定
return authorizationStatus == .sharingAuthorized
// ✅ 正しい判定
return authorizationStatus != .notDetermined
```
### 問題2: 実際のデータアクセス確認の欠如
認証状態だけでなく、**実際にデータクエリが成功するかの確認**が必要です。
## 解決方法
### 1. 認証判定ロジックの修正
```swift
public var isAuthorized: Bool {
checkAuthorizationStatus()
// HealthKit では .notDetermined 以外は権限確認済みとして扱う
// 実際のアクセス可否はデータ取得時のエラーで判断する
return authorizationStatus != .notDetermined
}
```
### 2. 実際のデータアクセステストの実装
```swift
public func requestAuthorization() async throws -> Bool {
let readTypes: Set<HKObjectType> = [
HKQuantityType.quantityType(forIdentifier: .stepCount)!,
]
try await healthStore.requestAuthorization(toShare: [], read: readTypes)
// 認証状態だけでなく、実際にデータが取得できるかもチェック
let isActuallyAuthorized = await checkActualDataAccess()
return isActuallyAuthorized
}
/// 実際にデータアクセスが可能かチェック
/// HealthKit は認証状態とは別に、実際のデータ取得で権限を確認する必要がある
private func checkActualDataAccess() async -> Bool {
guard let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount) else {
return false
}
let calendar = Calendar.current
let now = Date()
let startOfDay = calendar.startOfDay(for: now)
let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay) ?? now
let predicate = HKQuery.predicateForSamples(
withStart: startOfDay,
end: endOfDay,
options: .strictStartDate
)
return await withCheckedContinuation { continuation in
let query = HKStatisticsQuery(
quantityType: stepCountType,
quantitySamplePredicate: predicate,
options: .cumulativeSum
) { _, statistics, error in
if let error = error {
print("HealthKit actual access test failed: \(error)")
continuation.resume(returning: false)
return
}
// エラーなくクエリが完了すれば、実際にアクセス権限がある
print("HealthKit actual access test succeeded")
continuation.resume(returning: true)
}
healthStore.execute(query)
}
}
```
### 3. データ取得メソッドの改善
```swift
public func getTodayStepCount() async throws -> Int {
// まず認証状態をチェック
if authorizationStatus == .notDetermined {
throw HealthKitError.notAuthorized
}
guard let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount) else {
throw HealthKitError.queryFailed
}
let calendar = Calendar.current
let now = Date()
let startOfDay = calendar.startOfDay(for: now)
let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay) ?? now
let predicate = HKQuery.predicateForSamples(
withStart: startOfDay,
end: endOfDay,
options: .strictStartDate
)
return try await withCheckedThrowingContinuation { continuation in
let query = HKStatisticsQuery(
quantityType: stepCountType,
quantitySamplePredicate: predicate,
options: .cumulativeSum
) { _, statistics, error in
if let error = error {
continuation.resume(throwing: error)
return
}
let stepCount = statistics?.sumQuantity()?.doubleValue(for: .count()) ?? 0.0
continuation.resume(returning: Int(stepCount))
}
healthStore.execute(query)
}
}
```
## デバッグのコツ
### 詳細ログの追加
```swift
public func getDetailedAuthorizationInfo() -> (status: HKAuthorizationStatus, description: String) {
guard let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount) else {
return (.notDetermined, "stepCount type could not be created")
}
let status = healthStore.authorizationStatus(for: stepCountType)
let description: String
switch status {
case .notDetermined:
description = "User has not yet been asked for authorization"
case .sharingDenied:
description = "User has denied authorization"
case .sharingAuthorized:
description = "User has authorized sharing"
@unknown default:
description = "Unknown authorization status"
}
return (status, description)
}
```
### 認証フローの可視化
```swift
private func loadTodaySteps() async {
// 詳細な認証状態をログ出力
let authInfo = healthKitService.getDetailedAuthorizationInfo()
print("HealthKit authorization status: \(authInfo.status.rawValue) - \(authInfo.description)")
if !healthKitService.isAuthorized {
print("HealthKit not authorized, requesting authorization...")
let granted = try await healthKitService.requestAuthorization()
print("HealthKit authorization request result: \(granted)")
}
}
```
## まとめ
### HealthKit 認証のベストプラクティス
1. **認証状態は `.notDetermined` 以外を「確認済み」として扱う**
2. **実際のデータクエリでアクセス権限を最終確認する**
3. **詳細ログを追加してデバッグしやすくする**
4. **プライバシー保護の仕様を理解した実装にする**
### 他のプライバシー重視フレームワークへの応用
この手法は、HealthKit 以外の Apple のプライバシー重視フレームワークでも応用できます:
- **Photos**: 写真ライブラリアクセス
- **Contacts**: 連絡先アクセス
- **Location**: 位置情報アクセス
### 参考資料
- [potatotips でHealthKitの権限に苦労した話 - dely Tech Blog](https://tech.dely.jp/entry/potatetips_86)
- [Apple Developer Documentation - HealthKit](https://developer.apple.com/documentation/healthkit)
- [WWDC Sessions - HealthKit](https://developer.apple.com/videos/healthkit)
---
HealthKit の認証は一見複雑に見えますが、プライバシー保護という Apple の哲学を理解すれば、適切な実装ができるようになります。実際のデータアクセステストを組み合わせることで、ユーザーにとって分かりやすく、開発者にとってもデバッグしやすいアプリを作ることができます。 コメントはまだありません