如何验证网站是否可以通过 Swift 访问?

How to verify that a website is reachable with Swift?

我的应用程序应访问托管网站上的 php 文件,以便从后端 SQL 数据库获取数据。这工作正常,但我想做好准备或各种可能的错误。如果没有互联网连接或无法访问主机,则会抛出错误 - 没问题。但是如果 url 地址被修改为主机上不存在的地址,则不会抛出错误。但我也想涵盖这种情况。 Swift 中最好的方法是什么?

这是我的代码:

    @available(iOS 15.0, *)
   func checkCustomerExistsInBackend(emailAddress: String) async throws -> String 
   {
    
    let url = URL(string: "https://myHost.de/mySite/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    
    let dataString = "EmailAddress=\(emailAddress)"
    var returnValue = ""
    do {
        let dataD = dataString.data(using: .utf8)
        let (data, _) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)
        let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
        returnValue = answer.Message
    }
    catch {
        let myError: NSError = error as NSError
        switch myError.localizedDescription {
        case "The Internet connection appears to be offline.":
            throw BackendError.noInternet
        case "A server with the specified hostname could not be found.":
            throw BackendError.serverNotFound
        default:
            throw error
        }
    }
    return returnValue
}

上面的url“https://myHost.de/mySite/checkCustomerexists.php”当然不是真实地址。但是当我用真实的主机地址替换“myHost.de”时,即使站点“mySite”不存在,也不会抛出任何错误。

我花了几个小时在 SO 中寻找答案,但找不到适合我星座的任何东西。

如有任何提示,我们将不胜感激!

Larme 的评论回答了这个问题。如果它对任何跨过同一主题的人有帮助,这里是我的示例的修改代码以及基于 Larme 的建议的解决方案:

   @available(iOS 15.0, *)
func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {
    
    let url = URL(string: "https://myHost.de/mySite/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    
    let dataString = "EmailAddress=\(emailAddress)"
    var returnValue = ""
    do {
        let dataD = dataString.data(using: .utf8)
        let (data, response) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)
       
        let httpURLResponse = response as? HTTPURLResponse
        let statusCode = httpURLResponse?.statusCode
        if statusCode != 404 {
            let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
            returnValue = answer.Message
        }
        else {
            throw BackendError.invalidURL
        }
    }
    catch {
        let myError: NSError = error as NSError
        print(myError.localizedDescription)
        switch myError.localizedDescription {
        case "The Internet connection appears to be offline.":
            throw BackendError.noInternet
        case "A server with the specified hostname could not be found.":
            throw BackendError.serverNotFound
        default:
            throw error
        }
    }
    return returnValue
}