How to Ping External host from Swift in iOS?

SwiftiOSApps/ApplicationsMobile Development

Sometime you may require to ping an external website and check whether it’s up and running before you do any processing or fire request on the same.

Here we will be seeing how to check whether the external website is up and running.

Let’s being by Creating new project

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “PingMe”

Step 2 − Open ViewController.swift and add the function checkIsConnectedToNetwork() and add the following code.

func checkIsConnectedToNetwork() {
   let hostUrl: String = "https://google.com"
   if let url = URL(string: hostUrl) {
      var request = URLRequest(url: url)
      request.httpMethod = "HEAD"
      URLSession(configuration: .default)
      .dataTask(with: request) { (_, response, error) -> Void in
         guard error == nil else {
            print("Error:", error ?? "")
            return
         }
         guard (response as? HTTPURLResponse)?
         .statusCode == 200 else {
            print("The host is down")
            return
         }
         print("The host is up and running")
      }
      .resume()
   }
}

Step 3 − Now call this function from viewDidLoad method.

Your final code should look like

import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
      self.checkIsConnectedToNetwork()
   }
   func checkIsConnectedToNetwork() {
      let hostUrl: String = "https://google.com"
      if let url = URL(string: hostUrl) {
         var request = URLRequest(url: url)
         request.httpMethod = "HEAD"
         URLSession(configuration: .default)
         .dataTask(with: request) { (_, response, error) -> Void in
            guard error == nil else {
               print("Error:", error ?? "")
               return
            }
            guard (response as? HTTPURLResponse)?
            .statusCode == 200 else {
               print("The host is down")
               return
            }
            print("The host is up and running")
         }
         .resume()
      }
   }
}

When you run above code you can see ("The host is up and running") is printed on your console.

You can alternatively create a button on a UI and on tap of that button fire a request and can print on a textfield too.

raja
Published on 09-May-2019 08:00:03
Advertisements