无法让Selector适用于我的Swift功能

Gar*_*tes 1 objective-c selector oauth-2.0 gtm-oauth2 swift

我有一个混合的Swift和Objective C应用程序.swift应用程序使用一些ObjectiveC库来处理OAuth2身份验证.其中一部分是对令牌的OAuth2请求完成后对委托方法的回调.

以下代码正在Objective C库(GTMOAuth2)中执行,该库使用我传入的选择器:

if (delegate_ && finishedSelector_) {
  SEL sel = finishedSelector_;
  NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel];
  NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
  [invocation setSelector:sel];
  [invocation setTarget:delegate_];
  [invocation setArgument:&self atIndex:2];
  [invocation setArgument:&auth atIndex:3];
  [invocation setArgument:&error atIndex:4];
  [invocation invoke];
}
Run Code Online (Sandbox Code Playgroud)

我想要调用的函数是在我的swift viewController中,看起来像这样:

func authentication(viewController: GTMOAuth2ViewControllerTouch, finishedWithAuth: GTMOAuth2Authentication, error: NSError)
{
    if (error != nil)
    {
        var alertView: UIAlertView = UIAlertView(title: "Authorisation Failed", message: error.description, delegate: self, cancelButtonTitle: "Dismiss")

        alertView.show()

    }
    else
    {
        // Authentication Succeeded
        self.mytoken = finishedWithAuth.accessToken
    }
}
Run Code Online (Sandbox Code Playgroud)

我目前传入的选择器是:

let mySelector: Selector = Selector("authentication:viewController:finishedWithAuth:error:")
Run Code Online (Sandbox Code Playgroud)

并在此调用中用作参数:

let myViewController: GTMOAuth2ViewControllerTouch = GTMOAuth2ViewControllerTouch(authentication: auth, authorizationURL: authURL, keychainItemName: nil, delegate: self, finishedSelector: mySelector)
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么我的功能永远不会被调用?它总是在创建NSInvocation的行上失败.

我尝试了多个选择器字符串,每个选择器字符串似乎都失败了.我错过了什么吗?

我也尝试将"@objc"放在func名称前面,但无济于事.

Mar*_*n R 5

Swift方法

func authentication(viewController: GTMOAuth2ViewControllerTouch,
                  finishedWithAuth: GTMOAuth2Authentication,
                             error: NSError)
Run Code Online (Sandbox Code Playgroud)

暴露于Objective-C为

-(void)authentication:(GTMOAuth2ViewControllerTouch *) viewController 
     finishedWithAuth:(GTMOAuth2Authentication *) finishedWithAuth
                error:(NSError *)error
Run Code Online (Sandbox Code Playgroud)

这意味着选择器是

Selector("authentication:finishedWithAuth:error:")
Run Code Online (Sandbox Code Playgroud)

通常,第一个参数名称不是选择器的一部分.唯一的例外是init方法,其中第一个参数名称合并到Objective-C方法名称中.例如,Swift初始化程序

init(foo: Int, bar: Int) 
Run Code Online (Sandbox Code Playgroud)

转换为Objective-C as

- (instancetype)initWithFoo:(NSInteger)foo bar:(NSInteger)bar
Run Code Online (Sandbox Code Playgroud)

而选择器将是

Selector("initWithFoo:bar:")
Run Code Online (Sandbox Code Playgroud)