Swift HealthKit update Birthday - ios

I want to update the birthday in Apple Health. But I don't know how.
This is my authorization func:
private func requestAuthorisationForHealthStore() {
let dataTypesToWrite = [
HKCharacteristicType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
]
let dataTypesToRead = [
HKCharacteristicType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
]
self.healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite),
readTypes: NSSet(array: dataTypesToRead), completion: {
(success, error) in
if success { println("User completed authorisation request.") }
else { println("The user cancelled the authorisation request. \(error)") }
})
}
For requesting the birthday I call my function:
func requestAgeAndUpdate() {
var error: NSError?
let dob = self.healthStore?.dateOfBirthWithError(&error)
if error != nil {
println("There was an error requesting the date of birth: \(error)")
return
}
self.ageLabel.text = "\(dob)"
}
But how I can change/update the birthday programmatically?
Thanks for help!

You cannot change these characteristics programatically. The user must enter this data via the Health App.
From the documentation
The HKCharacteristicType class is a concrete subclass of the
HKObjectType class. HealthKit uses characteristic types to represent
data that does not typically change over time. Unlike the other object
types, characteristic types cannot be used to create new HealthKit
objects. Instead, users must enter and edit their characteristic data
using the Health app. Characteristic types are used only when asking
for permission to read data from the HealthKit store.

HealthKit Framework Reference;
https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HealthKit_Framework/index.html#//apple_ref/doc/uid/TP40014707
HealthKit objects can be divided into two main groups: characteristics
and samples. Characteristic objects represent data that typically does
not change. This data includes the user’s birthdate, blood type, and
biological sex. Your application cannot save characteristic data. The
user must enter or modify this data using the Health app.

Related

Read Blood group, Age, Gender etc from HealthKit in Swift

I am trying to read Personal Details (Blood group, Age, Gender) of Healthkit but unable to request for that.
As per Apple Doc here:
HealthKit provides five characteristic types: biological sex, blood
type, birthdate, Fitzpatrick skin type, and wheelchair use. These
types are used only when asking for permission to read data from the
HealthKit store.
But i can't make add HKCharacteristicType in authorisation request.
I have run Apple Sample Project which requests for:
HKQuantityTypeIdentifier.stepCount.rawValue,
HKQuantityTypeIdentifier.distanceWalkingRunning.rawValue,
HKQuantityTypeIdentifier.sixMinuteWalkTestDistance.rawValue
But when I add
HKCharacteristicTypeIdentifier.bloodType.rawValue
HKCharacteristicTypeIdentifier.dateOfBirth.rawValue
The permission screen does not asks for DOB and Blood Type. See Image:
Configuration: Simulator iOS 15.4 and Xcode 13.3
Anyone knows that if we can access Personal Data of HealthKit or not. Please help me out.
This is happening because bloodType and dateOfBirth are of type HKCharacteristicType
when you call this, the compactMap operation will not include your types
private static var allHealthDataTypes: [HKSampleType] {
let typeIdentifiers: [String] = [
HKQuantityTypeIdentifier.stepCount.rawValue,
HKQuantityTypeIdentifier.distanceWalkingRunning.rawValue,
HKQuantityTypeIdentifier.sixMinuteWalkTestDistance.rawValue,
HKCharacteristicTypeIdentifier.bloodType.rawValue,
HKCharacteristicTypeIdentifier.dateOfBirth.rawValue
]
return typeIdentifiers.compactMap { getSampleType(for: $0) }
}
check getSampleType:
func getSampleType(for identifier: String) -> HKSampleType? {
if let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: identifier)) {
return quantityType
}
if let categoryType = HKCategoryType.categoryType(forIdentifier: HKCategoryTypeIdentifier(rawValue: identifier)) {
return categoryType
}
return nil
}
your types won't fall into any of these if let, so this function will return nil. You must change the code so you are able to use HKCharacteristicTypeIdentifier as well.
EDIT: An easy way to do this is changing the readDataTypes in HealthData class to:
static var readDataTypes: [HKObjectType] {
return allHealthDataTypes + [
HKObjectType.characteristicType(forIdentifier: .dateOfBirth)!,
HKObjectType.characteristicType(forIdentifier: .bloodType)!
]
}
You can only request read authorization for the HKCharacteristicTypes, not share authorization. Update your code to add these 2 data types only to the readDataTypes variable. Right now you are requesting both read & share for the characteristic types, which is why they are not appearing on the authorization sheet.

Swift how to Create Multipage Form and Save Data to Firebase?

I have successfully installed Firebase and connected the login and registration with UID. If the user saves additional data in the app, I would now like to assign this to the respective user who is logged in, what is the best way to do this? Sorry I'm a beginner in Swift and Firebase, I need a tutorial or an explanation that is not too complex.
Thank you all
Uikit
Swift 5
Firebase
All of this is assuming you have Firebase UserAuth connected with your app and setup.
All users have a UID, user identifier, that uniquely identifies them. This is easy to get.
//there must be a user signed in
let user = Auth.auth().currentUser
let uid = user.uid
Simply put, to store data that is unique to the user, store it all under the uid using Firestore. If you do not have Firestore, get started with Firestore.
All data you save to Firestore, must be structured in a dictionary format with String as the key and Any as the value. For example, if I wanted to store the top 3 favorite flavors of ice cream for a user, you would do this *note firebase will create these documents and collections for you automatically if they do not exist so do not panic *:
//First get a reference to the database.
// It is best to have db as a global variable
let db = Firestore.firestore()
let favoriteFlavors: [String: Any] = ["numberOne":flavorOne as Any, "numberTwo":flavorTwo as Any, "numberThree": flavorThree as Any]
//access the collection of users
//access the collection of the currentUser
//create a document called favoriteFlavors
//set the document's data to the dictionary
db.collection("users").collection(uid).document("favoriteFlavors").setData(favoriteFlavors) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
Now, when you want to retrieve this data, you do access the users collection, the collection of the logged in user, then read the favoriteFlavors document--like this:
let docRef = db.collection("users").collection(uid).document("favoriteFlavors")
docRef.getDocument { (document, error) in
if let document = document {
print("Document received")
// retrieve the data in the document (a dictionary)
let data = document.data()
} else {
print("Document does not exist")
}
}
So if you wanted to get the number one favorite flavor, you would do this:
//Remember that data is a dictionary of String:Any
if let numberOneFlavor = data["numberOne"] as? String {
print("Number one favorite flavor ",numberOneFlavor)
}
Granted, this can get more convoluted, but this is a solid foundation of what you need to know. I advice reading the add data and get data pages of the Firestore documentation.

iOS Health Kit Clinical Patient Data

I have a third-party app that is attempting to gather clinical health records from the iOS Health App. I have successfully followed these steps to gain access to apple healths 7 record types. For the requirements of this task, I also need to gain access to "Patient Data". This data can be found within the Apple Health App under accounts:
In the "FHIR Patient Data" tab:
Does the apple health kit API allow for this type of data fetch?
The answer to your question is yes, the API supports retrieval of FHIR records. You will have to pull the data apart yourself after you get it. Here is some example code which will get the records;
func getClinicalDocuments()
{
guard let cdaType = HKObjectType.documentType(forIdentifier: .CDA) else {
print("unable to create CDA type.")
return
}
allDocuments.removeAll(keepingCapacity: true)
let cdaQuery = HKDocumentQuery(documentType: cdaType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil, includeDocumentData: true)
{ (query, results, done, error) in
if results != nil
{
for d in results!
{
self.allDocuments.append(d as! HKCDADocumentSample)
}
}
}
healthStore.execute(cdaQuery)
}

check if firebase write operation was successful in iOS

How to check if firebase real time write operation was successful in ios?
I am trying to store data to real time database using the following code but it does not work:-
//adding the artist inside the generated unique key
refArtists.child(key!).setValue(data) { (error, dbreference) in
if error != nil{
print(error?.localizedDescription)
} else {
print("success", dbreference)
}
}
and I also tried following:-
let key = refArtists.childByAutoId().key
//creating artist with the given values
let artist = ["id":key,
"latitude": "34234" as String,
"longitude": "67657" as String
]
let data = ["data": artist]
refArtists.child(key!).setValue(data)
I am unable to understand why my write operation is unsuccessful.
Edit from comments:
The closure does not get called. I am getting this error :
Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Firebase error. Please ensure that you spelled the name of your Firebase correctly.

Is it possible to delete a HealthKit entry from my app?

I'm making an app with HealthKit and want to try to add a swipe to delete on my table view. I know there is a healthStore.delete option, but will this delete from the Health app and how would I know which HKSample to delete from HealthKit.
The HKSample class is an abstract class. Thus you should should never instantiate a HKSample object directly. Instead, you always work with one of the subclasses of HKSample (HKCategorySample, HKQuantitySample, HKCorrelation, or HKWorkout classes) where HKSampleClass1 would be one of the subclasses.
healthStore.deleteObject(HKSampleClass1) { (success: Bool, error: NSError?) -> Void in {
if success () {
//success in deletion
}
}}
In the first step, you need to define your specific key in HKMetadataKeySyncIdentifier before you save your data to apple health.
And then, you can use HKMetadataKeySyncIdentifier to delete specific health data.
let healthKitStore = HKHealthStore()
// SAVE
var meta = [String: Any]()
meta[HKMetadataKeySyncVersion] = 1
meta[HKMetadataKeySyncIdentifier] = "specific key"
let recordSample = HKQuantitySample(type: type, quantity: quantity, start: date, end: date, metadata: meta)
healthKitStore.save(bloodGlucoseSample) { success, error in
if success {
print("saving record to health success")
} else {
print("saving record to health error = \(String(describing: error))")
}
}
// DELETE
let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeySyncIdentifier, allowedValues: ["specific key"])
healthKitStore.deleteObjects(of: bloodGlucoseType, predicate: predicate) { success, _, error in
if success {
print("delete health record success")
} else {
print("delete health record error = \(String(describing: error))")
}
}
Yes, calling healthStore.deleteObject() will delete the sample from Health. However, keep in mind that your app may only delete samples that it saved to HealthKit.
You'll need to perform a query to retrieve the samples you want to show to the user. You could use HKSampleQuery or HKAnchoredObjectQuery.

Resources