簡體   English   中英

使用Swift 4 Ping網站或IP地址(或檢查網站是否在線)?

[英]Ping a Website or an IP Address (or Check if a Website is Online) using Swift 4?

我從昨天開始一直在尋找一個更簡單的解決方案,只需ping一個網站並檢查它是否在Swift中返回200。

但我發現的只是目標C中的解決方案。

在Swift中,我找到了一些答案

func pingHost(_ fullURL: String) {
        let url = URL(string: fullURL)

        let task = URLSession.shared.dataTask(with: url!) { _, response, _ in
            if let httpResponse = response as? HTTPURLResponse {
                print(httpResponse.statusCode)
            }
        }

        task.resume()
    }

但是當我從其他一些函數中調用它時

self.pingHost("https://www.google.com")

它給出了奇怪的錯誤

2018-09-26 12:46:34.076938+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 1
2018-09-26 12:46:35.082274+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 2
2018-09-26 12:46:36.083497+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 3
2018-09-26 12:46:37.083964+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:5 Err:-1 Errno:1 Operation not permitted
2018-09-26 12:46:37.084497+0530 Net Alert[1608:52682] [] nw_resolver_create_dns_service_locked [C1] DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
2018-09-26 12:46:37.087264+0530 Net Alert[1608:52682] TIC TCP Conn Failed [1:0x600003706e80]: 10:-72000 Err(-65563)
2018-09-26 12:46:37.088841+0530 Net Alert[1608:52673] Task <2B08658D-5DFA-48E9-A306-A47ED130DD1F>.<1> HTTP load failed (error code: -1003 [10:-72000])
2018-09-26 12:46:37.088990+0530 Net Alert[1608:52673] Task <2B08658D-5DFA-48E9-A306-A47ED130DD1F>.<1> finished with error - code: -1003

我如何只是簡單地在Swift 4中ping並檢查它是否返回200?

如果您要“ping”某個網站,則需要使用HEAD請求而不是GET請求。 要查看網站是否已啟動,您不需要整個網站,只需要標題。 它將節省時間和帶寬:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

if let url = URL(string: "https://apple.com") {
  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("down")
          return
      }

      print("up")
    }
    .resume()
}

(如果沒有在操場上跑步,請省略操場上的東西。)

我想問題很簡單:你啟用了App Sandbox,沒有檢查 Outgoing Connections

你的pingHost方法怎么樣 - 這是完全正確的。 所以我認為唯一的問題是App Sandbox設置。

在此輸入圖像描述

如果你正在開發MacOS Anton的答案是正確的。 如果您正在為iOS開發,但如果您正在ping非安全URL,則需要禁用App Transport Security(ATS) 為了做到這一點,你需要設置NSAllowsArbitraryLoadstrueNSAppTransportSecurity在Info.plist的領域。

有關更多信息, 訪問: https//developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html - NSAppTransportSecurity

您可以使用第三方庫來實現相同的目標。

https://github.com/ankitthakur/SwiftPing

let pingInterval:TimeInterval = 3
let timeoutInterval:TimeInterval = 4
let configuration = PingConfiguration(pInterval:pingInterval, 
withTimeout:  timeoutInterval)

print(configuration)

SwiftPing.ping(host: "google.com", configuration: configuration, 
queue: DispatchQueue.main) { (ping, error) in
print("\(ping)")
print("\(error)")

}

SwiftPing.pingOnce(host: "google.com", configuration: 
configuration, 
queue: DispatchQueue.global()) { (response: PingResponse) in
print("\(response.duration)")
print("\(response.ipAddress)")
print("\(response.error)")

}

class PingResponse : NSObject {

public var identifier: UInt32

public var ipAddress: String?

public var sequenceNumber: Int64

public var duration: TimeInterval

public var error: NSError?

}

https://github.com/naptics/PlainPing

PlainPing.ping("www.google.com", withTimeout: 1.0, completionBlock: { 
(timeElapsed:Double?, error:Error?) in
if let latency = timeElapsed {
    self.pingResultLabel.text = "latency (ms): \(latency)"
}

if let error = error {
    print("error: \(error.localizedDescription)")
}
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM