0

I want to allow users to create some items while they are offline. then send created items to backend when the user reconnect to internet.
I am confused, What's the proper way to achieve that?

  • Should I use waitsforconnectivity of URLSession and it will send the request even when the user close the app
  • Or should I schedule a background task? if so then how to trigger this task when user connect to the internet?

Notes: I am using Alamofire for networking

Dot Freelancer
  • 4,083
  • 3
  • 28
  • 50

2 Answers2

0

I think you're overcomplicating this.

If you're using Alamofire for networking then I wouldn't suggest the first approach as that would be mixing the usage of URLSession and Alamofire for networking and that's not a great idea.

In terms of your second approach. Why does it need to be a background task? Why can't you just check if the user is first connected to the internet, and if they are you can proceed normally. If not, then just create items and cache them somehow. Then when you reconnect to the internet you can send the cached items first as you would send normal items.

Alamofire has a built in NetworkReachabilityManager which will help you determine your network status. There's a nice example in this answer for using it.

Mr.P
  • 1,390
  • 13
  • 35
  • thanks for replaying, I am trying to secure sending created data to server. I don't want to wait utile the user open the app to send these requests. – Dot Freelancer Dec 11 '19 at 10:01
0

You can use Alomafire itself do that: NetworkManager

class NetworkManager {

//shared instance
static let shared = NetworkManager()

let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")

func startNetworkReachabilityObserver() {

    reachabilityManager?.listener = { status in
        switch status {

            case .notReachable:
                print("The network is not reachable")

            case .unknown :
                print("It is unknown whether the network is reachable")

            case .reachable(.ethernetOrWiFi):
                print("The network is reachable over the WiFi connection")

            case .reachable(.wwan):
                print("The network is reachable over the WWAN connection")

            }
        }

        // start listening
        reachabilityManager?.startListening()
   }
}

Reachability Observer

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // add network reachability observer on app start
        NetworkManager.shared.startNetworkReachabilityObserver()

        return true
    }
}
Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75