Testing the connection from client to server is essential when developing a client/server application.
The idea of this is to use a URLSession to send a request to the server and check if the return date string exists.
func checkConnection(completionHandler:@escaping (_ isOnline: Bool?) -> Void){ let stringurl = "http://" + "Your Server IP" let url = NSURL(string: stringurl) let task = URLSession.shared.dataTask(with: url! as URL) {(data, response, error) in let httpResponse = response as? HTTPURLResponse if (httpResponse?.allHeaderFields["Date"] as? String) != nil { let isConnected = true completionHandler(isConnected) }else{ let isConnected = false completionHandler(isConnected) } } task.resume() }
Usage: Put the code below into any function you want to use.
checkConnection { (isOnline) -> Void in let status = isOnline! DispatchQueue.main.async{ if status{ // Do something when connected }else{ // Do something when disconnected } } }
You can also use this idea to get server time data in swift. This is useful when you develop an application that needs time synchronization between the client and server. >>> See more.