[英]Pass objective-c completion handler to swift
使用ios pushkit didReceiveIncomingPushWithPayload; 调用并传递多个参数,包括 withCompletionHandler。 withCompletionHandler 的函数调用、接口和 swift 参数是什么样的?
AppDelegate.m
- (void)pushRegistry:(PKPushRegistry *)registry
didReceiveIncomingPushWithPayload:(PKPushPayload *)payload
forType:(PKPushType)type
withCompletionHandler:(void (^)(void))completion{
NSLog(@"VHC: AppDelegate - didReceiveIncomingPushWithPayload hit!");
Voip* instance = [Voip new];
[instance handleIncomingPush:payload forType:type withCompletionHandler:completion];
}
语音文件
-(void)handleIncomingPush: (PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion;
网络电话
@objc(handleIncomingPush: : :)
func handleIncomingPush(_ payload: PKPushPayload, forType: PKPushType, withCompletionHandler: @escaping () -> Void) {
withCompletionHandler()
}
错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Voip handleIncomingPush:forType:withCompletionHandler:]: unrecognized selector sent to instance 0x2806f4f30'
几个观察:
@objc
方法名称不对。 鉴于您的 Swift 方法签名与您在 Objective-C 代码中寻找的内容相匹配,您只需删除手动方法名称:
class Voip: NSObject { @objc func handleIncomingPush(_ payload: PKPushPayload, forType: PKPushType, withCompletionHandler: @escaping () -> Void) { withCompletionHandler() } }
或者,就个人而言,如果需要,我会使用 Swiftier 方法签名并声明 ObjC 接口:
class Voip: NSObject { @objc(handleIncomingPush:forType:withCompletionHandler:) func handleIncomingPush(_ payload: PKPushPayload, type: PKPushType, completionHandler: @escaping () -> Void) { completionHandler() } }
删除Voip.h
标头。 一直只使用“Objective-C 生成的接口头文件”。
不要在 Objective-C 代码中导入Voip.h
,而是导入生成的接口标头。 例如,如果您的应用名为MyApp
,那么它可能只是:
#import <MyApp-Swift.h>
如果您不清楚名称是什么,请查看“Objective-C Generated Interface Header File”设置的目标设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.