Search code examples
parse-platformoffline

Parse Platform Online mode and fallback for offline if timeout/network issue


Is there a way in Parse Platform to fallback to local data store if there is no connection ?

I understand that there is pin/pinInBackground, so I can pin any object to the LocalDataStore.

Then I can query the localdatastore to get that info.

However, I want always to try to get first the server data, and if it fails, get the local data.

Is there a way to do this automatically?

(or I have to pin everything locally, then query remote and if it fails, then query locally)


Solution

  • Great question.

    Parse has the concept of cached queries. https://docs.parseplatform.org/ios/guide/#caching-queries

    The interesting feature of cached queries is that you can specify - "if no network". However this only works if you have previously cached the query results. I've also found that the delay between losing network connectivity and the cached query recognising that its lost network makes the whole capability a bit rubbish.

    How I have resolved this issue is using a combination of the AlamoFire library and pinning objects. The reason I chose to use the AlamoFire library is because it's extremely well supported and it spots drops in network connectivity near immediately. I only have a few hundred records so I'm not worrying about pinning objects and definitely performance does not seem to be affected. So how I work this is....

    Define some class objects at the top of the class

    // Network management
    private var reachability: NetworkReachabilityManager!
    private var hasInternet: Bool = false
    

    Call a method as the view awakes

    // View lifecycle
    override func awakeFromNib() {
            super.awakeFromNib()
            self.monitorReachability()
        }
    

    Update object when network availability changes. I know this method could be improved.

    private func monitorReachability() {
            NetworkReachabilityManager.default?.startListening { status in
                if "\(status)" == "notReachable" {
                    self.hasInternet = false
                } else {
                    self.hasInternet = true
                }
                print("hasInternet = \(self.hasInternet)")
            }
        }
    

    Then when I call a query I have a switch as I set up the query object.

    // Start setup of query
    let query = PFQuery(className: "mySecretClass")
    
    if self.hasInternet == false {
        query.fromLocalDatastore()
        }
    // Complete rest of query configuration
    

    Of course I pin all the results I ever return from the server.