How to Read healthkit data and send to server when app is in background in below iOS 13 version


if #available(iOS 10.0, *) {

let center = UNUserNotificationCenter.current()

let content = UNMutableNotificationContent()

content.title = "Background Fetch"

content.subtitle = "fetch working"

content.body = "background fetch is working fine"

content.sound = UNNotificationSound.default()

let requ = UNNotificationRequest(identifier: "ContentIdentifier", content: content, trigger: nil)


if var urlComponents = URLComponents(string: "*****") {

urlComponents.query = "media=music&entity=song&term=\(searchTerm)"

guard let url = urlComponents.url else {

return

}

dataTask =

defaultSession.dataTask(with: url) { [weak self] data, response, error in

defer {

self?.dataTask = nil

}


if let error = error {

self?.errorMessage += "DataTask error: " +

error.localizedDescription + "\n"

} else if

let data = data,

let response = response as? HTTPURLResponse,

response.statusCode == 200 {


UserDefaults.standard.set("Success", forKey: "backgroundFetch")

center.add(requ, withCompletionHandler: { (error) in

if error != nil {

UserDefaults.standard.set("localsucess", forKey: "LocalNotificationsuccess")

}

})


completionHandler(.newData)



DispatchQueue.main.async {


completionHandler(.failed)


completion(self?.tracks, self?.errorMessage ?? "")

}

}

}

dataTask?.resume()

}

Replies

Half the battle is knowing what classes to look for. The WWDC videos are a good start to finding your answers.


TLDW, here are the things you're looking for.


For discussion purposes, if you wanted to make a step counter application, that monitors progress throughout the day and sends local notifications when milestones have been met, I would take a look at one of these two long-running queries:


1. https://developer.apple.com/documentation/healthkit/hkanchoredobjectquery

2. https://developer.apple.com/documentation/healthkit/hkobserverquery


As for getting the background updates, refer to: https://developer.apple.com/documentation/healthkit/hkhealthstore/1614175-enablebackgrounddelivery


Jump down to the discussion and view the note, depending on the type of data you want to collect, you can get throttled.


"Note

Some data types, such as step counts, have a minimum frequency of

HKUpdateFrequency.hourly
. This frequency is enforced transparently."


Make sure you're clear and up front with your user about this data you're going to collect and send to your server. Privacy is important.