Bogdan Bogdanov
Bogdan Bogdanov

Reputation: 992

Delete added sample in Health App

I add sample like this:

var store:HKHealthStore?
date = NSDate()
let type = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryVitaminA)
quantity = HKQuantity(unit: HKUnit.gramUnitWithMetricPrefix(.Micro), doubleValue: 100)
let sample = HKQuantitySample(type: type, quantity: quantity, startDate: date, endDate: date)
store.saveObject(sample, withCompletion: { (success, error) -> Void in
            if(error != nil) {
                println("Error saving sample: \(error.localizedDescription)")
            }else{
                println("Sample saved successfully!")
            }
        })

And when I want to delete this sample I execute:

store.deleteObject(sample, withCompletion: {(success, error) -> Void in
    if(error != nil) {
        println("Error deleting sample: \(error.localizedDescription)")
    }else{
        println("Sample deleted successfully!")
    }
})

And it returns me: Error deleting sample: object not found Everytime I use the same 'date' for startDate and endDate. I've tryed with let sample = HKQuantitySample(type: type, quantity: quantity, startDate: date, endDate: date, metadata: metadata) where metadata is let metadata = [HKMetadataKeyExternalUUID:"\(Int64(date.timeIntervalSince1970))"], but also unsuccessfully...

Upvotes: 8

Views: 2905

Answers (2)

Bhanu Prakash
Bhanu Prakash

Reputation: 1483

It is not possible to delete the Health data which is entered by ApplicationA in ApplicationB, other than Apple's Health app.

As per Apple's documentation, it is possible to delete the health data which is created by the respective application only. Though, user given write permission, it is not possible to delete some other applications health data from your application, but it is possible from Apple's Health application only.

From the documentation:

NOTE

Although your app can manage only the objects it created and saved, the users can delete any data they want using the Health app.

Upvotes: 2

maurer83
maurer83

Reputation: 11

I actually got some help from Apple with this exact problem, but I haven't yet solved it. You are coding this the exact same way I did, but they told me the problem is that that we are creating a new sample and then trying to delete it immediately. The sample doesn't exist yet, so it returns an item not found error.

What needs to be done (in theory) is to run an HKSampleQuery and then perform the delete with the object returned from that. That object already exists in HealthKit and can be deleted.

Hope that helps!

EDIT : Solved it... I found that my date/time stamp was TOO strict. I modified my startDate / endDate to return MM/DD/YYYY format and samples were deleted properly. Hope that helps you!

Upvotes: 1

Related Questions