我需要从Swift调用Objective C方法

时间:2015-04-24 14:52:29

标签: objective-c swift

我在Objective C中有这个接口,我试图从Swift调用它,它似乎不属于完成代码。不确定我错过了什么!

@interface WPLogin : NSObject

/*!
 * @brief Logs into the application returning success or failure with an error     object.
 * If login is successful the credential is automatically stored
 *
 * @param serverURLString   Address to login to
 * @param username  Username to login with
 * @param password  Password for user
 * @param completion Completion block to be called after attempting login
 */
- (void)loginToURL:(NSString *)serverURLString
      withUsername:(NSString *)username
              password:(NSString *)password
        completion:(void (^)(WPLoginStatus success, NSError * error))completion;

@end

来自Swift的调用函数看起来像这样......

    var uid = "test"
    var pwd = "test"
    var url = "http://www.google.com"
    var loginAuth = WPLogin();

        loginAuth.loginToURL(url, withUsername: uid, password: pwd, completion: { (status:WPLoginStatus, error:NSError!) -> Void in
            println("Inside Login")
    })

桥接文件

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "WPLogin.h"

适用于Objective C的版本

if (!self.login) {
    self.login = [WPLogin new];
}

[self.login loginToURL:url
                       withUsername:uid
                           password:pwd
                         completion:^(WPLoginStatus status, NSError *error) {
                                NSLog(@"complete");
                          }];

1 个答案:

答案 0 :(得分:1)

问题是在Swift版本中,WPLogin对象是局部变量var loginAuth)。因此它在有机会之前就已经死了。将它作为属性,与Objective-C版本(self.login)一样:

class MyClass {
    var login : WPLogin = WPLogin()
    func myMethod () {
        var uid = "test"
        var pwd = "test"
        var url = "http://www.google.com"
        self.login.loginToURL(url, withUsername: uid, password: pwd, completion: { 
            (status:WPLoginStatus, error:NSError!) -> Void in
            println("Inside Login")
        })
    }
}

此对象需要随时间采取行动 - 在Internet上运行,登录,调用完成处理程序 - 如果它立即死亡,它就无法执行此操作,就像在Swift代码中一样。它必须持续过了很长时间。