[英]Call Swift completion handler in objective c
I am trying to call a swift method, which is implemented like this:- 我试图调用一个swift方法,它实现如下: -
@objc class DataAPI: NSObject {
func makeGet(place:NSString , completionHandler: (String! , Bool!) -> Void)
{
var str:String = ""
let manager = AFHTTPSessionManager()
manager.GET("https://api.com", parameters: nil, success:
{ (operation, responseObject) -> Void in
str = "JSON: \(responseObject!.description)"
print(str)
completionHandler(str,false) //str as response json, false as error value
},
failure: { (operation,error: NSError!) in
str = "Error: \(error.localizedDescription)"
completionHandler("Error",true)
})
}}
Now when I am trying to call it in my Objective C class, it is throwing an error "No Visible interface for DataAPI declares selector makeGet:completionHandler" 现在当我试图在我的Objective C类中调用它时,它抛出一个错误“没有可见的DataAPI接口声明选择器makeGet:completionHandler”
This is how I am calling the method in my Objective C class:- 这就是我在Objective C类中调用方法的方法: -
[[DataAPI new] makeGet:@"" completionHandler:^{
}];
I see that in Swift
the completion handler has two arguments: String
and Bool
whereas in your Objective-C
call you pass a block without any arguments. 我在Swift
看到,完成处理程序有两个参数: String
和Bool
而在Objective-C
调用中,你传递一个没有任何参数的块。 I think it may be the cause of the error. 我认为这可能是错误的原因。
Try: 尝试:
[[DataAPI new] makeGet:@"" completionHandler:^(NSString* string, BOOl b){
}];
Try to clean and Rebuild to generate the "YourModule-Swift.h" again with all your changes. 尝试清理并重建以再次生成“YourModule-Swift.h”并进行所有更改。 Then it should be something like this: 那应该是这样的:
[[DataAPI new] makeGet:@"" withCompletionHandler:^(NSString* string, BOOl b){
// your code here
}];
If you still getting that error, your "YourModule-Swift.h" file hasn't been generated correctly. 如果仍然出现该错误,则表示尚未正确生成“YourModule-Swift.h”文件。 Check it! 核实!
You shouldn't use !(ImplicitUnwrappedOptional) keyword in closure. 你不应该在闭包中使用!(ImplicitUnwrappedOptional)关键字。 That is not allow bridging to ObjC code. 这不允许桥接到ObjC代码。 just remove ! 只是删除! from closure. 从关闭。
func makeGet(place:NSString , completionHandler: (String! , Bool!) -> Void)
to 至
func makeGet(place:NSString , completionHandler: (String , Bool) -> Void)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.