Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift call Objective-C wrapper function containing blocks

I have an Objective-C wrapper (ObjCWrapper.h and ObjCWrapper.m) with prototype

+ (void) login:(NSString *)username andPassword:(NSString *)password andErrorBlock:(SuccessBlock)errorBlock andSuccessBlock:(SuccessBlock)successBlock;

With typedef

typedef void (^SuccessBlock)(NSString *);

and implementation

+ (void)login:(NSString *)username andPassword:(NSString *)password andErrorBlock:(SuccessBlock)errorBlock andSuccessBlock:(SuccessBlock)successBlock
{
    // do stuff like
    successBlock(@"test");
}

From my swift view controller (ViewController.swift), I call the login function:

ObjCWrapper.login("abc", andPassword: "abc",
        andErrorBlock:
        {
            (error:String) -> Void in
            println();
        },
        andSuccessBlock:
        {
            (map:String) -> Void in
            println();
        }
    )

But I get error:

Cannot invoke 'login' with an argument list of type '(String, andPassword: String, andErrorBlock:(String)->void, andSuccessBlock:(String)->void)'

Searching in google says that I am passing some invalid types in the arguments, but I can't find anything wrong in the code. Removing the blocks from the function makes the code work, so I guess it is something related on the way of calling a block function.

Thanks for the help!

like image 926
Grace Avatar asked Nov 26 '25 07:11

Grace


1 Answers

It might be worth adding nullability specifiers to your completion block:

typedef void (^SuccessBlock)( NSString * _Nonnull );

And to the method itself:

+ (void) login:(nonnull NSString *)username andPassword:(nonnull NSString *)password andErrorBlock:(nullable SuccessBlock)errorBlock andSuccessBlock:(nullable SuccessBlock)successBlock;

Then you should be able to call your method in Swift:

        ObjCWrapper.login("login", andPassword: "pass", andErrorBlock: { (error:String) -> Void in
        //error handling
        }) { (map:String) -> Void in
            //other stuff
    }
like image 107
Adam Avatar answered Nov 28 '25 20:11

Adam