具有多个参数的函数的选择器

Selector for a function with multiple parameters

我需要我的应用程序扩展来使用参数打开我的主机应用程序。我这样做是通过使用 UIApplication.shared.

打开自定义 URL

现在。我的最后一个版本在试飞中被拒绝,并显示一条消息 "Need test for export compliance" 或类似的东西(iTunes connect 不想 运行 英文)。所以我认为我的扩展 Build Settings 中的 Require only App-Extension-Safe API 设置为 NO 是问题的可能原因。

将标志设置为 YES 将禁用 UIApplication.shared。所以我决定使用我前段时间在这里找到的旧方法(不幸的是,找不到记录):

// Get "UIApplication" class name through ASCII Character codes.
NSString *className = [[NSString alloc] initWithData:[NSData dataWithBytes:(unsigned char []){0x55, 0x49, 0x41, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E} length:13] encoding:NSASCIIStringEncoding];
if (NSClassFromString(className))
{
    //  A different way to call [UIApplication sharedApplication]
    id object = [NSClassFromString(className) performSelector: @selector(sharedApplication)];
    //  These lines invoke selector with 3 arguments
    SEL selector = @selector(openURL:options:completionHandler:);
    id  (*method)(id, SEL, id, id, id) = (void *)[object methodForSelector: selector];
    method(object, selector, myURL, nil, nil);
    //  Close extension
    [self.extensionContext completeRequestReturningItems: @[] completionHandler: nil];
}

如您所见,这是Objective-C,但我还需要使其成为Swifty。 所以这就是我卡住的地方:

let codes = [CUnsignedChar](arrayLiteral: 0x55, 0x49, 0x41, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E)
let className = String(data: Data(bytes: UnsafeRawPointer(codes), count: 13), encoding: String.Encoding.ascii) ?? ""
if NSClassFromString(className) != nil
{
    let object = NSClassFromString(className)?.shared()
    let sel = #selector(_:options:completionHandler:)
    let meth = object?.method(for: sel)
    ...

问题在于 sel(预期表达式)。我在这里尝试引用的方法是

open(_:options:completionHandler:) 

这东西

#selector(open(_:options:completionHandler:))

也不起作用(使用未解析的标识符),因为我在其中实现此代码的视图控制器没有这样的方法。

所以问题是:如何创建一个带有一些参数的无名选择器引用,以便稍后与我的 meth 对象一起使用?谢谢。

您可以使用 NSSelectorFromString 方法,该方法允许您使用 String.

声明 Selector 个实例

我没有完整的源代码,但经过一些调整,以下应该可以工作:

NSSelectorFromString("open(_:options:completionHandler:)")

有关此方法的更多文档可用 here