I need to perform a DB insert into MongoDB Atlas using a scheduled background task in SwiftUI. Unfortunately, at the last step when I actually perform the insert, the request never resolves leading to a insert failure.
@main
struct ExampleApp: SwiftUI.App {
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
HomeScreen()
}
.onChange(of: scenePhase) { newScenePhase in
// ...
case .background:
scheduleAppRefresh()
// ...
}
}
.backgroundTask(.appRefresh("pushData")) {
if let realmApp = realmApp {
guard let user = realmApp.currentUser else {
return
}
let client = user.mongoClient("mongodb-atlas")
let database = client.database(named: "ExampleDB")
let collection = database.collection(withName: "Activities")
let height: Document = ["activityKey": "height", "startDate": AnyBSON(Date()), "endDate": AnyBSON(Date()), "value": 1.9, "unit": "m"]
await addActivityToMongo(height: height, collection: collection)
}
}
}
func addActivityToMongo(height: Document, collection: RealmSwift.MongoCollection) async {
print("Inserting into MongoDB")
do {
let objectId = try await collection.insertOne(height)
print("Successfully inserted a document with id: \(objectId)")
} catch {
print("Error writing to MongoDB: \(error.localizedDescription)")
}
}
func scheduleAppRefresh() {
let backgroundTask = BGAppRefreshTaskRequest(identifier: "pushData")
backgroundTask.earliestBeginDate = Date(timeIntervalSinceNow: 0)
try? BGTaskScheduler.shared.submit(backgroundTask)
print("Successfully scheduled a background task")
}
}
I have added pushData
to Info.plist under Permitted background task scheduler identifiers
and the backgroundTask
runs successfully but await collection.insertOne(height)
never resolves - Xcode output just shows Inserting into MongoDB
which I have printed until I bring the app again to the foreground at which point it fails with
ERROR: The network connection was lost.
Call to MongoDB failed: The network connection was lost
Marking simulated task complete: <BGAppRefreshTask: pushData>
Is there something that I am missing to actually make this work? Thanks