Check Internet connection availability?

前端 未结 4 1964
悲哀的现实
悲哀的现实 2021-01-17 19:20

I just need to check the internet connection availability before start communicating with the service in my iphone App. I am using Swift 1.2 and Xcode 6 as my development en

4条回答
  •  情书的邮戳
    2021-01-17 19:58

    I was looking to solve the same problem for myself this morning and I felt that this "Reachability" sample code provided from Apple does not appeal to me at all (mostly because of the manual opening of sockets and the SystemConfiguration ugly API).

    Instead of this I tried to make a simple HTTP connection to a random non-existing URL using Alamofire (I already had it as a dependency) and check the value in the error that I would receive.

    Alamofire.request(.GET, "http://superrandomdomainnamethatisnotused.com/superrandompath").responseString {
        (request, response, stringData, error) in
    
        if let networkError = error {
            if (networkError.code == -1009) {
                println("No Internet \(error)")
            }
        }
    }
    

    This code could be rewritten using any other networking library. Error -1009 is corresponding to NSURLErrorNotConnectedToInternet which is somewhat more reassuring way of saying "you are really not connected to the Internet".

    Another good thing is that this works even if you put non-existing URL, which means that you don't have to make a successful HTTP request to any server even if you have Internet connection.

    The downside is that the code in the block is executed asynchronously, which could be inconvenience depending on your requirements.

提交回复
热议问题