Check for internet connection with PFQueryTableViewController in Swift

70 Views Asked by At

I have an app I'm working on that is linked with Parse, so I'm using a PFQueryTableViewController.

I would simply like to know how I can do a check for an internet connection when I run the app.

Currently, If I turn off my internet connection then run the app, I get the loading spinner for the table, but obviously, nothing ever loads. Eventually, the spinner stops and I'm just left with a blank table.

I've read about using Reachability, but not really sure about how to put this into my current app.

essentially, what I'd like, is every time the user starts the app, it does a check for internet connection, and if there is then great! If not, it shows an alert to say No Connection.

Can someone help please? I've added my code for the queryForTable() function which is where I'm thinking this check should happen. Let me know if you need to see any other of my code. Thanks

override func queryForTable() -> PFQuery {

    let query = PFQuery(className: "Reviews")

    if indexArray == 0 {

        query.orderByDescending("createdAt")

    } else if indexArray == 1 {

        query.orderByAscending("FilmName")

    } else if indexArray == 2 {

        query.orderByDescending("OurRating")

    } else if indexArray == 3 {

        query.orderByAscending("OurRating")

    } else if indexArray == 4 {

        query.orderByDescending("WantToSeeThisCount")

    } else if indexArray == 5 {

        query.orderByAscending("DirectedBy")

    } else if indexArray == 6 {

        query.orderByDescending("UpVoteCount")

    } else if indexArray == 7 {

        query.orderByDescending("DownVoteCount")

    }

    query.whereKey("ToDisplayInApp", equalTo:true)

    // Add a where clause if there is a search criteria
    if filmSearchBar.text != "" {

        query.whereKey("FilmName", containsString: filmSearchBar.text!)

    }

    return query

}
1

There are 1 best solutions below

0
KrishnaCA On
var reachability: Reachability!

func checkNetworkReachability() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(functionToHandleWhenConnectionChanges()), name:kReachabilityChangedNotification, object: nil)

    if self.reachability == nil {
        self.reachability = Reachability.reachabilityForInternetConnection()
        self.reachability.startNotifier()
    }
}

func functionToHandleWhenConnectionChanges() {
     // self.reachability.isReachable() returns a boolean. If it's yes, then you are connected to internet, otherwise not connected.
}

Before doing all this, add Reachability.h and Reachability.m files from https://github.com/tonymillion/Reachability

Hope this helps :)