Call Swift completion handler in objective c
Asked Answered
S

3

5

I am trying to call a swift method, which is implemented like this:-

@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"

This is how I am calling the method in my Objective C class:-

[[DataAPI  new] makeGet:@"" completionHandler:^{
}];
Sacrilegious answered 17/8, 2016 at 9:54 Comment(1)
can you help its not working in swift 5 :(Goldeneye
P
2

You shouldn't use !(ImplicitUnwrappedOptional) keyword in closure. That is not allow bridging to ObjC code. just remove ! from closure.

func makeGet(place:NSString , completionHandler: (String! , Bool!) -> Void)

to

func makeGet(place:NSString , completionHandler: (String , Bool) -> Void)
Parquetry answered 17/8, 2016 at 10:4 Comment(0)
A
4

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. I think it may be the cause of the error.

Try:

[[DataAPI  new] makeGet:@"" completionHandler:^(NSString* string, BOOl b){
}];
Alyosha answered 17/8, 2016 at 9:56 Comment(1)
That code is not working Andrey, but thanks for pointing out the issue. +1Sacrilegious
S
3

Try to clean and Rebuild to generate the "YourModule-Swift.h" again with all your changes. 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. Check it!

Summer answered 23/8, 2018 at 14:0 Comment(0)
P
2

You shouldn't use !(ImplicitUnwrappedOptional) keyword in closure. That is not allow bridging to ObjC code. just remove ! from closure.

func makeGet(place:NSString , completionHandler: (String! , Bool!) -> Void)

to

func makeGet(place:NSString , completionHandler: (String , Bool) -> Void)
Parquetry answered 17/8, 2016 at 10:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.