'connection(_:didReceive:)' 的使用不明确

Ambiguous use of 'connection(_:didReceive:)'

static let didReceiveResponseSelector : Selector = #selector((NSURLConnectionDataDelegate.connection(_:didReceive:)) as (NSURLConnectionDataDelegate) ->(NSURLConnection,URLResponse) -> ())

此代码返回错误:

Ambiguous use of 'connection(_:didReceive:)'

我在 GitHub 上参考了 Apple 的官方进化线程,我尊重语法但不起作用:

Referencing the Objective-C selector of a method

NSURLConnectionDataDelegate 是一个协议,您不能使用 NSURLConnectionDataDelegate.connection(_:didReceive:) 创建选择器,您必须使用 NSURLConnectionDataDelegate 的实现,例如:

class YourDelegateImplementation: NSURLConnectionDataDelegate {
     public func connection(_ connection: NSURLConnection, didReceive data: Data) {
     }
}

然后您可以像这样创建一个选择器:

let yourDelegate: YourDelegateImplementation = YourDelegateImplementation()
let yourSelector : Selector = #selector(yourDelegate.connection(_:didReceive:))

不要投射选择器:

let didReceiveResponseSelector = #selector(NSURLConnectionDelegate.connection(_:didReceive:))

还值得注意的是,委托函数 connection(_ connection: NSURLConnection, didReceive challenge: URLAuthenticationChallenge) 已被弃用,取而代之的是 connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge)

已解决,只需添加“?”:

    static let didReceiveResponseSelector : Selector = #selector((NSURLConnectionDataDelegate.connection(_:didReceive:)) as ((NSURLConnectionDataDelegate) -> (NSURLConnection,URLResponse) -> void)?)