Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธี Ping ตรวจสอบ External Host ใน iOS ด้วย Swift

บางครั้งต้อง Ping ตรวจสอบเว็บไซต์ภายนอกว่ายังทำงานอยู่ก่อนส่ง Request จริง

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → New Project → Single View Application → ชื่อ "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()
self.checkIsConnectedToNetwork()
}
// ... ฟังก์ชัน checkIsConnectedToNetwork() วางไว้ที่นี่
}

รันโค้ด จะเห็น "The host is up and running" ใน Console

วิธี Ping ตรวจสอบ External Host ใน iOS ด้วย Swift

สามารถปรับเป็นปุ่มกดตรวจสอบและแสดงผลใน TextField ได้