简体   繁体   中英

Call Objective C method with blocks from Swift

I am implementing Matrix messaging into my iOS app using their MatrixKit framework which I added to my project via Cocoapods. I have everything working except for one final issue: one of the provided methods isn't recognized in my Swift file. The MXSession.h file lists a method:

- (void)start:(void (^)(void))onServerSyncDone
  failure:(void (^)(NSError *error))failure NS_REFINED_FOR_SWIFT;

which is used to start an MXSession. I need to call this method from my Swift class, and I have tried to following to no avail:

session.start({
   //success 
}, failure: {
   //failure   
})

The compiler complains that Value of type 'MXSession' has no member 'start' when it clearly does. Also, strangely, I am able to access other methods in MXSession, such as:

- (void)resume:(void (^)(void))resumeDone;

The following:

session.resume {
    //resumed successfully
}

works perfectly. I am not too comfortable with closures in swift, am I simply making a syntax error? I have tried everything and can't seem to make it work.

Well, of course I solved it the instant I posted this question. Apparently the NS_REFINED_FOR_SWIFT macro appends two underscores to the beginning of the method for use in swift. The following code compiles:

session.__start({
    //success
}, failure: { error in
    //failure
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM