如何在 iOS 中從 Swift ping 外部主機?


有時您可能需要 Ping 外部網站,並在對網站進行任何處理或傳送請求之前檢查它是否正在執行。

我們將在此處瞭解如何檢查外部網站是否正在執行。

讓我們從建立新專案開始

步驟 1 − 開啟 Xcode → 新建專案 → 單檢視應用程式 → 給它命名為“PingMe”

步驟 2 − 開啟 ViewController.swift 並新增 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()
   }
}

步驟 3 − 現在從 viewDidLoad 方法呼叫此函式。

最終程式碼看起來應如下所示

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()
      }
   }
}

執行上述程式碼時,您可以看到控制檯中列印著 (“該主機正在執行”)。

此外,您還可以在 UI 上建立一個按鈕,並單擊該按鈕來發送請求,還可以列印在文字欄位中。

更新時間: 2019 年 7 月 30 日

941 次瀏覽

開啟你的職業

完成課程後獲得認證

開始
廣告