Swift - 无法为dispatch_time_t类型调用初始化程序

时间:2017-03-30 12:36:41

标签: swift

我已经接管了一些Swift 2代码并尝试将其提升到Swift 3(Xcode 8.3),但我被困在一条线上。

代码正在检查主机是否已连接:

func isHostConnected(hostAddress : String) -> Bool {
    let request = NSMutableURLRequest(url: NSURL(string: hostAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!)! as URL)
    request.timeoutInterval = 3
    request.httpMethod = "HEAD"

    let session = URLSession(configuration: URLSessionConfiguration.default)
    var responseCode = -1

    let group = DispatchGroup.init()
    group.enter()

    session.dataTask(with: request as URLRequest, completionHandler: {(_, response, _) in
        if let httpResponse = response as? HTTPURLResponse {
            responseCode = httpResponse.statusCode
        }
        group.leave()
    }).resume()

    group.wait(timeout: dispatch_time_t(DispatchTime.distantFuture)) //ERROR LINE
    return (responseCode == 401)
}

我收到错误:

group.wait(timeout: dispatch_time_t(DispatchTime.distantFuture))

其中包括:

Cannot invoke initializer for type 'dispatch_time_t' with an argument list of type '(DispatchTime)'

所以它似乎正在寻找DispatchTime类型的对象作为参数,但我似乎无法在Google上找到匹配.distantFuture的答案

另外,如果我尝试:

group.wait(timeout: dispatch_time_t(.distantFuture))

我收到错误说:

Type of expression is ambiguous without more context

感谢。

2 个答案:

答案 0 :(得分:1)

实际上它更简单:)

group.wait(timeout: .distantFuture)

或者如果你想等5秒钟:

group.wait(timeout: .now() + .seconds(5))

美丽的权利

另见this way better answer

除此之外......你应该考虑@vadian在评论中所说的内容:)

希望有所帮助。

答案 1 :(得分:1)

首先,要回答你的问题,它只是

s/\.?/ - /

其次,在这种情况下等待的编程习惯非常糟糕。根本没有理由。异步通知的最有效方法是使用完成处理程序。

代码少得多,代码使用Swift 3原生结构group.wait(timeout: .distantFuture) URL,并考虑了防止崩溃的错误网址:

URLRequest

并使用它:

func isHostConnected(hostAddress : String, completion: @escaping (Bool)->()) {
    guard let escapedString = hostAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed),
          let url = URL(string: escapedString) else {
             completion(false)
             return
    }
    var request = URLRequest(url: url)
    request.timeoutInterval = 3
    request.httpMethod = "HEAD"

    let session = URLSession(configuration: URLSessionConfiguration.default)
    session.dataTask(with: request, completionHandler: {(_, response, _) in
        if let httpResponse = response as? HTTPURLResponse {
            completion(httpResponse.statusCode == 401)
        }
        completion(false)
    }).resume()
}