Hello,
I am currently developing an iOS application using SensorKit. I encountered an issue when attempting to fetch SensorKit data in the background using background tasks (appRefresh, processing). The following error occurs:
In the delegate function func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, failedWithError error: any Error) {}, I receive the error: SRErrorDataInaccessible.
In code specific manner:
start and handle background fetch (appRefresh)
func handleAppRefreshTask(task: BGAppRefreshTask) {
logger.logWithServer(level: .default, message: "background fetch start", category: String(describing: BackgroundTaskManager.self))
scheduleBackgroundFetch()
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
let fetchOperation = FetchOperation()
queue.addOperation(fetchOperation)
task.expirationHandler = {
self.logger.logWithServer(level: .error, message: "background fetch expirated", category: String(describing: BackgroundTaskManager.self))
queue.cancelAllOperations()
}
fetchOperation.completionBlock = {
task.setTaskCompleted(success: !fetchOperation.isCancelled)
}
}
Background fetch operation class
class FetchOperation: Operation {
override func main() {
guard !isCancelled else { return }
Task {
// this function will execute fetch request for all user allowed sensorReader, 'func fetch(_ request: SRFetchRequest)'
await SensorkitManager.shared.startFetchAndUpload()
}
}
}
I have the following questions:
- Is it possible to fetch SensorKit data in the background?
- If it is possible, why does the above error occur?
- If it is possible, could you provide the solution code and the correct workflow to avoid this error?
Thank you.
I found the cause. SensorKit cannot send fetch requests when the user's device is locked. (That’s probably why the error occurred.)
Therefore, it is possible to send fetch requests for SensorKit data in the background, but the device must be unlocked.
If my solution is incorrect, please let me know.