I am having trouble building a Swift/SwiftUI app that utilizes backgroundTask
and CoreLocation
. Specifically, I want to run a scheduled, daily background task that fetches the user's location and then sends a message to my server saying that the fetch was successful. I was wondering if this was at all possible with "Allow While In Use" authorization, as opposed to "Always Allow". I don't think I need to reference didUpdateLocations
. I just need to fetch location once in the background task. Also, could I somehow guarantee that the background task run?
import SwiftUI
import UserNotifications
import BackgroundTasks
import CoreLocation
@main
struct ExampleApp: App {
@Environment(\.scenePhase) private var phase
var body: some Scene {
WindowGroup {
ContentView()
}
.onChange(of: phase) { newPhase in
switch newPhase {
case .background: scheduleAppRefresh()
default: break
}
}
.backgroundTask(.appRefresh("com.exampleapp.task")) {
await fetchLocation()
}
}
}
func fetchLocation() async {
let location = CLLocationManager()
location.requestWhenInUseAuthorization()
location.requestLocation()
print(location.location?.coordinate.latitude)
print(location.location?.coordinate.longitude)
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.exampleapp.task")
request.earliestBeginDate = Date(timeIntervalSinceNow: 600) // 10 minutes
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}