Firestore Set Data Not Working in the Background

237 views Asked by At

I need my iOS app to save a bit of data to Firestore when it receives a remote notification in the background. It actually does save the data if it receives a remote notification within about 30 minutes of the app going into the background. However, if it receives the remote notification around an hour or more after it's gone into the background it doesn't set data.

It receives the notification as I can see the print statement in the console:

AppDelegate:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("Tada")
    
    if let dataString = userInfo["action"] as? String {
        let data = Data(base64Encoded: dataString)
        let jsonDecoder = JSONDecoder()
        let action = try! jsonDecoder.decode(RemoteInfo.self, from: data!)
        remoteDataManager.respondToRemoteAction(remoteData: action)
    }
    
    completionHandler(.newData)
}

RemoteDataManager:

func respondToRemoteCommand(remoteData: RemoteInfo) {
    
    // Some action that changes music playback, this always work!
    
    InfoClass.saveCurrentInfo(data: item)
}

It does trigger this function as it prints the statement into the console just before the setData function. However, it doesn't give me the "Successfully Saved Info Online" or "Error saving..." nor does it save to Firestore.

InfoClass:

static func saveCurrentInfo(data: Item) {

    let db = Firestore.firestore()
    let firebaseItem = try! FirebaseEncoder().encode(data)
    
    print("About to save")

    db.collection("Username").document("Item").setData([
        "Info" : firebaseItem
    ]) { (error) in
        if let e = error {
            print("Error saving: \(e)")
        } else {
            print("Successfully Saved Info Online")
        }
    }
}

As the code above hopefully shows, it does an action before setting data (changes the Music playback, which it always does each time it gets the remote notification), and triggers the saveCurrentInfo method, but stops just short of setData (it prints "About to save" each time).

It's like the app will only work for about 1-2 seconds and then gives up, but always when it gets to the Firebase set data function. I believe the app should do around 30 seconds of background work when receiving a remote notification before going inactive again.

How do I ensure the app completes the set data function?

0

There are 0 answers