xamarinxamarin.formsxamarin.iosbackground-processbackground-fetch

Xamarin.Forms iOS - start uploading data when device gets internet connectivity even when app is not currently active or is in the background


I have a Xamarin.Forms application where users create "listings" and then send them through to the server (Http api call). A use case we have is the user creates a listing but at the moment does not have internet connectivity so the listing will be sitting at a "pending" state. The user can then background the app (no longer active). At some point later on the user would now have internet connectivity, I want the app to automatically send those pending listings without the user having to open the app again.

I'm currently looking for a way to this in the iOS implementation of the Xamarin.Forms app and would also need to do something similar with Android implementation.

I've already looked at Background Fetch for iOS but at the moment it seems rare for PerformFetch to get called even if I set the interval to the backgroundfetchminimum so it might not be reliable enough. Also I have read on iOS docs that the code on PerformFetch should not run for more than 30 seconds otherwise it gets "penalized" and limit the interval even more. Listings can have large images or videos attached to them and it could certainly take more than 30 seconds to send all of them through.


Solution

  • NSUrlSessionUploadTask handles connectivity issue. You should also implement didCompleteWithError handler and queue the same upload again if the previous task went wrong.

    There is a nice github example from Rob Gibbens. He implements NSUrlSessionDownloadTask but you will use NSUrlSessionUploadTask instead with the same approach.

    Consider using MessagingCenter to have your code cleaner in your project.