OpenUV API Docs

device_hub

event_note

Support

account_balance
help_outline
headset_mic
Buy Me A Coffee

OpenUV Knowledge Base

Collection of useful tips about Sun Safety and Ultraviolet Radiation Index for Developers


UV Index Tracking with Apple Health Kit

Beginning with iOS 9, HealthKit has a number of new data types from external apps and accessories including the user’s exposure to ultraviolet (UV) radiation.

Below you could find an example of Swift helper class for getting Skin Type and saving UV Index using Apple HealthKit.

 import Foundation
import UIKit
import HealthKit

enum HealthKitError: Error {
 case notAvailable
 case notAuthorized
}

public class HealthKitHelper{

 public typealias Callback = (Result ) -> Void
 let healthKitStore = HKHealthStore()

 static let sharedInstance = HealthKitHelper()
 private init(){}

 public func checkAuthorization(callback: @escaping Callback){
   if HKHealthStore.isHealthDataAvailable()
   {
     let healthKitTypesToRead : Set = [
        HKObjectType.characteristicType(forIdentifier: .fitzpatrickSkinType)!,
        HKObjectType.quantityType(forIdentifier:.uvExposure)!,
     ]

     let healthKitTypesToWrite : Set = [
       HKObjectType.quantityType(forIdentifier: .uvExposure)!
     ]

     healthKitStore.requestAuthorization(
       toShare: healthKitTypesToWrite,
       read: healthKitTypesToRead,
       completion: { (success, error) in
         if (success) { callback(.Success()) }
         else { callback(.Failure(HealthKitError.notAuthorized)) }
       })
   }
   else
   {
     callback(.Failure(HealthKitError.notAvailable))
   }
 }

 public func saveUVIndex(uvIndex: Double, date: Date) {
   guard let uvIndexType = HKQuantityType.quantityType(forIdentifier: .uvExposure) else {
     fatalError("UV Index Type is no longer available in HealthKit")
   }

   let uvIndexQuantity = HKQuantity(unit: HKUnit.count(),
     doubleValue: uvIndex)

   let uvIndexSample = HKQuantitySample(type: uvIndexType,
     quantity: uvIndexQuantity,
     start: date,
     end: date)

   HKHealthStore().save(uvIndexSample) { (success, error) in
     if let error = error {
       print("Error Saving UVI Sample: \(error.localizedDescription)")
     } else {
       print("Successfully saved UVI Sample")
     }
   }
 }

 public func getSkinType() throws -> SkinType
 {
   do {
     let skinType =  try healthKitStore.fitzpatrickSkinType()
     let unwrappedSkinType = skinType.skinType
     switch unwrappedSkinType {
       case HKFitzpatrickSkinType.I: return SkinType.type1
       case HKFitzpatrickSkinType.II: return SkinType.type2
       case HKFitzpatrickSkinType.III: return SkinType.type3
       case HKFitzpatrickSkinType.IV: return SkinType.type4
       case HKFitzpatrickSkinType.V: return SkinType.type5
       case HKFitzpatrickSkinType.VI: return SkinType.type6
       case .notSet:
         return SkinType.type1
     }
   }
 }
}