-2

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)")
    }
}
  • You need to [edit] your question to include all relevant code in the form of a [mcve] in order to make the question on-topic. – Dávid Pásztor Aug 17 '23 at 14:17
  • "Specifically, I want to run a scheduled, daily background task..." The rest of the details aren't relevant. This is impossible. There is no way to schedule a task to run at a specific time or on a specific interval. I'll be duping this to the related question. If you believe there's more to this question, please update yours to explain the details, and we can reopen. If you can describe what user experience you're trying to create, there may be a better solution that does not require scheduled tasks. – Rob Napier Aug 17 '23 at 16:33
  • The linked response is from 2019 - didn't the `backgroundTask` API come after that? – Bassel Alesh Aug 18 '23 at 04:09
  • I saw some folks online try to use `backgroundTask` and get it to work, there's even a WWDC session on it here: https://developer.apple.com/videos/play/wwdc2022/10142/. Unfortunately I have not been able to get it to work on my device. I even tried sending `e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"name"]`, confirmed the task is setup properly, but still can never see it trigger on its own. – Bassel Alesh Aug 18 '23 at 04:12

0 Answers0