如何在 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 上创建一个按钮,并单击该按钮来发送请求,还可以打印在文本字段中。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP