How to retrieve healthkit data and display it?
I am working on a step app. I want to retrieve Healthkit data from the health app, but I don't know how to do it. I can't find anything on the internet. I want to get the steps data from the health app.
ios swift
add a comment |
I am working on a step app. I want to retrieve Healthkit data from the health app, but I don't know how to do it. I can't find anything on the internet. I want to get the steps data from the health app.
ios swift
Simple answer: Do some research. Then, if you have specific questions, come back and ask those. And While you're at it: Please that the tour and look at the help center.
– Burki
Feb 28 '17 at 10:48
add a comment |
I am working on a step app. I want to retrieve Healthkit data from the health app, but I don't know how to do it. I can't find anything on the internet. I want to get the steps data from the health app.
ios swift
I am working on a step app. I want to retrieve Healthkit data from the health app, but I don't know how to do it. I can't find anything on the internet. I want to get the steps data from the health app.
ios swift
ios swift
asked Feb 28 '17 at 8:40
BastiaanBastiaan
124
124
Simple answer: Do some research. Then, if you have specific questions, come back and ask those. And While you're at it: Please that the tour and look at the help center.
– Burki
Feb 28 '17 at 10:48
add a comment |
Simple answer: Do some research. Then, if you have specific questions, come back and ask those. And While you're at it: Please that the tour and look at the help center.
– Burki
Feb 28 '17 at 10:48
Simple answer: Do some research. Then, if you have specific questions, come back and ask those. And While you're at it: Please that the tour and look at the help center.
– Burki
Feb 28 '17 at 10:48
Simple answer: Do some research. Then, if you have specific questions, come back and ask those. And While you're at it: Please that the tour and look at the help center.
– Burki
Feb 28 '17 at 10:48
add a comment |
3 Answers
3
active
oldest
votes
For Asking permission asking permission
if HKHealthStore.isHealthDataAvailable() {
var writeDataTypes: Set<AnyHashable> = self.dataTypesToWrite()
var readDataTypes: Set<AnyHashable> = self.dataTypesToRead()
self.healthStore.requestAuthorization(toShareTypes: writeDataTypes, readTypes: readDataTypes, completion: {(_ success: Bool, _ error: Error) -> Void in
if !success {
print("You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: (error). If you're using a simulator, try it on a device.")
return
}
})
}
To write Data
func dataTypesToWrite() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
return Set<AnyHashable>([heightType, weightType, systolic, dystolic])
}
To read data from health kit
func dataTypesToRead() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
var sleepAnalysis: HKCategoryType? = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
var step: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
var walking: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
var cycling: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceCycling)
var basalEnergyBurned: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)
If you want to get the step count for last week then you can follow this bellow code
self.healthStore = HKHealthStore()
var calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents: DateComponents? = calendar.dateComponents([.day, .month, .year], from: Date())
anchorComponents?.hour = 0
var anchorDate: Date? = calendar.date(fromComponents: anchorComponents)
var quantityType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
// Create the query
var query = HKStatisticsCollectionQuery(quantityType, quantitySamplePredicate: nil, options: HKStatisticsOptionCumulativeSum, anchorDate: anchorDate, intervalComponents: interval)
// Set the results handler
query.initialResultsHandler = {(_ query: HKStatisticsCollectionQuery, _ results: HKStatisticsCollection, _ error: Error) -> Void in
if error != nil {
// Perform proper error handling here
print("*** An error occurred while calculating the statistics: (error?.localizedDescription) ***")
}
var endDate = Date()
var startDate: Date? = calendar.date(byAddingUnit: .day, value: -7, to: endDate, options: 0)
// Plot the daily step counts over the past 7 days
results.enumerateStatistics(from: startDate, to: endDate, block: {(_ result: HKStatistics, _ stop: Bool) -> Void in
var quantity: HKQuantity? = result.sumQuantity()
if quantity != nil {
var date: Date? = result.startDate
var value: Double? = quantity?.doubleValue(forUnit: HKUnit.count())
totalStepsCount = String(format: "%.f", value)
DispatchQueue.main.async(execute: {() -> Void in
self.calculateStepCountAndShow()
})
print("(date): (value)")
}
})
}
self.healthStore.executeQuery(query)
}
add a comment |
There are many tutorials on internet to use healthkit
to setup healthkit in your app and for permissions follow one of these tutorials
- follow official documentation
- Appcoda's HealthKit introduction
- Sample app tutorial and
- Raywenderlich tutorial
for example if we want to retrieve sleeping analysis data,
func retrieveSleepAnalysis() {
// first, we define the object type we want
if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) {
// Use a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if error != nil {
// something happened
return
}
if let result = tmpResult {
// do something with my data
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.InBed.rawValue) ? "InBed" : "Asleep"
print("Healthkit sleep: (sample.startDate) (sample.endDate) - value: (value)")
}
}
}
}
// finally, we execute our query
healthStore.executeQuery(query)
}
}
add a comment |
You need to enable healthkit
from project capabilities
then you will go through authentication
process, then you will start implementing a query
to retrieve the data using HKSampleQuery
, kindly follow this tutorial
as the code is long to be included here :)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42503863%2fhow-to-retrieve-healthkit-data-and-display-it%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
For Asking permission asking permission
if HKHealthStore.isHealthDataAvailable() {
var writeDataTypes: Set<AnyHashable> = self.dataTypesToWrite()
var readDataTypes: Set<AnyHashable> = self.dataTypesToRead()
self.healthStore.requestAuthorization(toShareTypes: writeDataTypes, readTypes: readDataTypes, completion: {(_ success: Bool, _ error: Error) -> Void in
if !success {
print("You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: (error). If you're using a simulator, try it on a device.")
return
}
})
}
To write Data
func dataTypesToWrite() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
return Set<AnyHashable>([heightType, weightType, systolic, dystolic])
}
To read data from health kit
func dataTypesToRead() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
var sleepAnalysis: HKCategoryType? = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
var step: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
var walking: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
var cycling: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceCycling)
var basalEnergyBurned: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)
If you want to get the step count for last week then you can follow this bellow code
self.healthStore = HKHealthStore()
var calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents: DateComponents? = calendar.dateComponents([.day, .month, .year], from: Date())
anchorComponents?.hour = 0
var anchorDate: Date? = calendar.date(fromComponents: anchorComponents)
var quantityType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
// Create the query
var query = HKStatisticsCollectionQuery(quantityType, quantitySamplePredicate: nil, options: HKStatisticsOptionCumulativeSum, anchorDate: anchorDate, intervalComponents: interval)
// Set the results handler
query.initialResultsHandler = {(_ query: HKStatisticsCollectionQuery, _ results: HKStatisticsCollection, _ error: Error) -> Void in
if error != nil {
// Perform proper error handling here
print("*** An error occurred while calculating the statistics: (error?.localizedDescription) ***")
}
var endDate = Date()
var startDate: Date? = calendar.date(byAddingUnit: .day, value: -7, to: endDate, options: 0)
// Plot the daily step counts over the past 7 days
results.enumerateStatistics(from: startDate, to: endDate, block: {(_ result: HKStatistics, _ stop: Bool) -> Void in
var quantity: HKQuantity? = result.sumQuantity()
if quantity != nil {
var date: Date? = result.startDate
var value: Double? = quantity?.doubleValue(forUnit: HKUnit.count())
totalStepsCount = String(format: "%.f", value)
DispatchQueue.main.async(execute: {() -> Void in
self.calculateStepCountAndShow()
})
print("(date): (value)")
}
})
}
self.healthStore.executeQuery(query)
}
add a comment |
For Asking permission asking permission
if HKHealthStore.isHealthDataAvailable() {
var writeDataTypes: Set<AnyHashable> = self.dataTypesToWrite()
var readDataTypes: Set<AnyHashable> = self.dataTypesToRead()
self.healthStore.requestAuthorization(toShareTypes: writeDataTypes, readTypes: readDataTypes, completion: {(_ success: Bool, _ error: Error) -> Void in
if !success {
print("You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: (error). If you're using a simulator, try it on a device.")
return
}
})
}
To write Data
func dataTypesToWrite() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
return Set<AnyHashable>([heightType, weightType, systolic, dystolic])
}
To read data from health kit
func dataTypesToRead() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
var sleepAnalysis: HKCategoryType? = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
var step: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
var walking: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
var cycling: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceCycling)
var basalEnergyBurned: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)
If you want to get the step count for last week then you can follow this bellow code
self.healthStore = HKHealthStore()
var calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents: DateComponents? = calendar.dateComponents([.day, .month, .year], from: Date())
anchorComponents?.hour = 0
var anchorDate: Date? = calendar.date(fromComponents: anchorComponents)
var quantityType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
// Create the query
var query = HKStatisticsCollectionQuery(quantityType, quantitySamplePredicate: nil, options: HKStatisticsOptionCumulativeSum, anchorDate: anchorDate, intervalComponents: interval)
// Set the results handler
query.initialResultsHandler = {(_ query: HKStatisticsCollectionQuery, _ results: HKStatisticsCollection, _ error: Error) -> Void in
if error != nil {
// Perform proper error handling here
print("*** An error occurred while calculating the statistics: (error?.localizedDescription) ***")
}
var endDate = Date()
var startDate: Date? = calendar.date(byAddingUnit: .day, value: -7, to: endDate, options: 0)
// Plot the daily step counts over the past 7 days
results.enumerateStatistics(from: startDate, to: endDate, block: {(_ result: HKStatistics, _ stop: Bool) -> Void in
var quantity: HKQuantity? = result.sumQuantity()
if quantity != nil {
var date: Date? = result.startDate
var value: Double? = quantity?.doubleValue(forUnit: HKUnit.count())
totalStepsCount = String(format: "%.f", value)
DispatchQueue.main.async(execute: {() -> Void in
self.calculateStepCountAndShow()
})
print("(date): (value)")
}
})
}
self.healthStore.executeQuery(query)
}
add a comment |
For Asking permission asking permission
if HKHealthStore.isHealthDataAvailable() {
var writeDataTypes: Set<AnyHashable> = self.dataTypesToWrite()
var readDataTypes: Set<AnyHashable> = self.dataTypesToRead()
self.healthStore.requestAuthorization(toShareTypes: writeDataTypes, readTypes: readDataTypes, completion: {(_ success: Bool, _ error: Error) -> Void in
if !success {
print("You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: (error). If you're using a simulator, try it on a device.")
return
}
})
}
To write Data
func dataTypesToWrite() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
return Set<AnyHashable>([heightType, weightType, systolic, dystolic])
}
To read data from health kit
func dataTypesToRead() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
var sleepAnalysis: HKCategoryType? = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
var step: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
var walking: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
var cycling: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceCycling)
var basalEnergyBurned: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)
If you want to get the step count for last week then you can follow this bellow code
self.healthStore = HKHealthStore()
var calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents: DateComponents? = calendar.dateComponents([.day, .month, .year], from: Date())
anchorComponents?.hour = 0
var anchorDate: Date? = calendar.date(fromComponents: anchorComponents)
var quantityType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
// Create the query
var query = HKStatisticsCollectionQuery(quantityType, quantitySamplePredicate: nil, options: HKStatisticsOptionCumulativeSum, anchorDate: anchorDate, intervalComponents: interval)
// Set the results handler
query.initialResultsHandler = {(_ query: HKStatisticsCollectionQuery, _ results: HKStatisticsCollection, _ error: Error) -> Void in
if error != nil {
// Perform proper error handling here
print("*** An error occurred while calculating the statistics: (error?.localizedDescription) ***")
}
var endDate = Date()
var startDate: Date? = calendar.date(byAddingUnit: .day, value: -7, to: endDate, options: 0)
// Plot the daily step counts over the past 7 days
results.enumerateStatistics(from: startDate, to: endDate, block: {(_ result: HKStatistics, _ stop: Bool) -> Void in
var quantity: HKQuantity? = result.sumQuantity()
if quantity != nil {
var date: Date? = result.startDate
var value: Double? = quantity?.doubleValue(forUnit: HKUnit.count())
totalStepsCount = String(format: "%.f", value)
DispatchQueue.main.async(execute: {() -> Void in
self.calculateStepCountAndShow()
})
print("(date): (value)")
}
})
}
self.healthStore.executeQuery(query)
}
For Asking permission asking permission
if HKHealthStore.isHealthDataAvailable() {
var writeDataTypes: Set<AnyHashable> = self.dataTypesToWrite()
var readDataTypes: Set<AnyHashable> = self.dataTypesToRead()
self.healthStore.requestAuthorization(toShareTypes: writeDataTypes, readTypes: readDataTypes, completion: {(_ success: Bool, _ error: Error) -> Void in
if !success {
print("You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: (error). If you're using a simulator, try it on a device.")
return
}
})
}
To write Data
func dataTypesToWrite() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
return Set<AnyHashable>([heightType, weightType, systolic, dystolic])
}
To read data from health kit
func dataTypesToRead() -> Set<AnyHashable> {
var heightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .height)
var weightType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bodyMass)
var systolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureSystolic)
var dystolic: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .bloodPressureDiastolic)
var sleepAnalysis: HKCategoryType? = HKObjectType.categoryType(forIdentifier: .sleepAnalysis)
var step: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
var walking: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)
var cycling: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .distanceCycling)
var basalEnergyBurned: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .basalEnergyBurned)
If you want to get the step count for last week then you can follow this bellow code
self.healthStore = HKHealthStore()
var calendar = Calendar.current
var interval = DateComponents()
interval.day = 1
var anchorComponents: DateComponents? = calendar.dateComponents([.day, .month, .year], from: Date())
anchorComponents?.hour = 0
var anchorDate: Date? = calendar.date(fromComponents: anchorComponents)
var quantityType: HKQuantityType? = HKObjectType.quantityType(forIdentifier: .stepCount)
// Create the query
var query = HKStatisticsCollectionQuery(quantityType, quantitySamplePredicate: nil, options: HKStatisticsOptionCumulativeSum, anchorDate: anchorDate, intervalComponents: interval)
// Set the results handler
query.initialResultsHandler = {(_ query: HKStatisticsCollectionQuery, _ results: HKStatisticsCollection, _ error: Error) -> Void in
if error != nil {
// Perform proper error handling here
print("*** An error occurred while calculating the statistics: (error?.localizedDescription) ***")
}
var endDate = Date()
var startDate: Date? = calendar.date(byAddingUnit: .day, value: -7, to: endDate, options: 0)
// Plot the daily step counts over the past 7 days
results.enumerateStatistics(from: startDate, to: endDate, block: {(_ result: HKStatistics, _ stop: Bool) -> Void in
var quantity: HKQuantity? = result.sumQuantity()
if quantity != nil {
var date: Date? = result.startDate
var value: Double? = quantity?.doubleValue(forUnit: HKUnit.count())
totalStepsCount = String(format: "%.f", value)
DispatchQueue.main.async(execute: {() -> Void in
self.calculateStepCountAndShow()
})
print("(date): (value)")
}
})
}
self.healthStore.executeQuery(query)
}
edited Feb 28 '17 at 9:11
answered Feb 28 '17 at 9:06
sumit kumarsumit kumar
17410
17410
add a comment |
add a comment |
There are many tutorials on internet to use healthkit
to setup healthkit in your app and for permissions follow one of these tutorials
- follow official documentation
- Appcoda's HealthKit introduction
- Sample app tutorial and
- Raywenderlich tutorial
for example if we want to retrieve sleeping analysis data,
func retrieveSleepAnalysis() {
// first, we define the object type we want
if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) {
// Use a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if error != nil {
// something happened
return
}
if let result = tmpResult {
// do something with my data
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.InBed.rawValue) ? "InBed" : "Asleep"
print("Healthkit sleep: (sample.startDate) (sample.endDate) - value: (value)")
}
}
}
}
// finally, we execute our query
healthStore.executeQuery(query)
}
}
add a comment |
There are many tutorials on internet to use healthkit
to setup healthkit in your app and for permissions follow one of these tutorials
- follow official documentation
- Appcoda's HealthKit introduction
- Sample app tutorial and
- Raywenderlich tutorial
for example if we want to retrieve sleeping analysis data,
func retrieveSleepAnalysis() {
// first, we define the object type we want
if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) {
// Use a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if error != nil {
// something happened
return
}
if let result = tmpResult {
// do something with my data
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.InBed.rawValue) ? "InBed" : "Asleep"
print("Healthkit sleep: (sample.startDate) (sample.endDate) - value: (value)")
}
}
}
}
// finally, we execute our query
healthStore.executeQuery(query)
}
}
add a comment |
There are many tutorials on internet to use healthkit
to setup healthkit in your app and for permissions follow one of these tutorials
- follow official documentation
- Appcoda's HealthKit introduction
- Sample app tutorial and
- Raywenderlich tutorial
for example if we want to retrieve sleeping analysis data,
func retrieveSleepAnalysis() {
// first, we define the object type we want
if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) {
// Use a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if error != nil {
// something happened
return
}
if let result = tmpResult {
// do something with my data
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.InBed.rawValue) ? "InBed" : "Asleep"
print("Healthkit sleep: (sample.startDate) (sample.endDate) - value: (value)")
}
}
}
}
// finally, we execute our query
healthStore.executeQuery(query)
}
}
There are many tutorials on internet to use healthkit
to setup healthkit in your app and for permissions follow one of these tutorials
- follow official documentation
- Appcoda's HealthKit introduction
- Sample app tutorial and
- Raywenderlich tutorial
for example if we want to retrieve sleeping analysis data,
func retrieveSleepAnalysis() {
// first, we define the object type we want
if let sleepType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis) {
// Use a sortDescriptor to get the recent data first
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// we create our query with a block completion to execute
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, tmpResult, error) -> Void in
if error != nil {
// something happened
return
}
if let result = tmpResult {
// do something with my data
for item in result {
if let sample = item as? HKCategorySample {
let value = (sample.value == HKCategoryValueSleepAnalysis.InBed.rawValue) ? "InBed" : "Asleep"
print("Healthkit sleep: (sample.startDate) (sample.endDate) - value: (value)")
}
}
}
}
// finally, we execute our query
healthStore.executeQuery(query)
}
}
edited Feb 28 '17 at 9:16
answered Feb 28 '17 at 8:59
varun aaruruvarun aaruru
2,08111135
2,08111135
add a comment |
add a comment |
You need to enable healthkit
from project capabilities
then you will go through authentication
process, then you will start implementing a query
to retrieve the data using HKSampleQuery
, kindly follow this tutorial
as the code is long to be included here :)
add a comment |
You need to enable healthkit
from project capabilities
then you will go through authentication
process, then you will start implementing a query
to retrieve the data using HKSampleQuery
, kindly follow this tutorial
as the code is long to be included here :)
add a comment |
You need to enable healthkit
from project capabilities
then you will go through authentication
process, then you will start implementing a query
to retrieve the data using HKSampleQuery
, kindly follow this tutorial
as the code is long to be included here :)
You need to enable healthkit
from project capabilities
then you will go through authentication
process, then you will start implementing a query
to retrieve the data using HKSampleQuery
, kindly follow this tutorial
as the code is long to be included here :)
answered Feb 28 '17 at 8:54
Alsh compilerAlsh compiler
8501924
8501924
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42503863%2fhow-to-retrieve-healthkit-data-and-display-it%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Simple answer: Do some research. Then, if you have specific questions, come back and ask those. And While you're at it: Please that the tour and look at the help center.
– Burki
Feb 28 '17 at 10:48