gpt4 book ai didi

objective-c - 我需要从 Swift 调用 Objective C 方法

转载 作者:行者123 更新时间:2023-11-30 10:16:12 26 4
gpt4 key购买 nike

我在 Objective C 中有这个接口(interface),我试图从 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");
}];

最佳答案

问题在于,在您的 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")
})
}
}

这个对象需要随着时间的推移采取行动 - 上网,登录,调用你的完成处理程序 - 如果它立即死亡,它就无法做到这一点,就像你的 Swift 代码中那样。它必须持续很长时间。

关于objective-c - 我需要从 Swift 调用 Objective C 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29850692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com