Search code examples
iosswiftcore-datagrand-central-dispatchalamofire

iOS - API Synchronization


I'm building a toy app in iOS where the user can:

  • Create tasks, stored locally
  • Those tasks will be synced to the server
  • Create tasks in a web page
  • They will be synced back to the app

All of this using Core Data for persistence and Alamofire for networking, coded in Swift.

What I usually do for this flow is the following:

  1. Upload new tasks
  2. Download changes from upstream
  3. Sync locally edited tasks

This requires that all of those tasks are executed serially, but Alamofire doesn't do synchronous requests apparently. I'm new to iOS programming, and I've read a little about GCD, but I'm not sure how should I proceed.

To clear this up with straightforward questions:

  1. Is that sync flow correct?
  2. Should I use GCD? If so, how?
  3. Any recommendations on how to do this properly?

Solution

  • This is how I'd do it (assuming you can change the server's code):

    First, store a local "sync date" somewhere in the app. Then, for every task, store a modified date. Whenever a task is modified, set the modified date to the current date. Then when you want to synchronise with the server:

    1. Upload all tasks modified after the "sync date" to the server. Also, send the "sync date" to the server.
    2. The server responds with all the tasks whose modified date is after the specified sync date.
    3. The server then goes through the uploaded items and saves them.
    4. The app then saves all the tasks downloaded from the server, creating new ones or updating existing ones as needed...
    5. The app then goes through all the items returned from the server, looking for the latest modified date. If the latest modified date is later than the app's "sync date", then set the "sync date" to the latest modified date.

    For deleting tasks, I'd have a "deleted" flag on each task. When a task is deleted, it's "deleted" flag is set to true. It'll still be synchronised to the server, but if a task is downloaded from the server with the "deleted" flag set, it should be removed from the database...

    GCD

    As for GCD, it looks like that Alamofire library takes care of all that for you, so you don't need to use it. If you did want to use it, it is pretty simple:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND), ^{
    
        // This code will run in the background, so it doesn't matter
        // how long it takes, it won't freeze the app...
    
    });
    
    dispatch_async(dispatch_get_main_queue(), ^{
    
        // This code will run on the main thread...
    
    });
    

    It also has a lot more features...