我需要从扩展程序内部执行主机应用程序。在Objective-C
中,我使用了以下内容:
// 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];
}
但是在Swift
中,我有几个问题:
UIApplication
不再具有sharedApplication
方法。相反,它具有类属性shared
。因此,我无法执行选择器来获得共享实例。我试图通过编写扩展名来绕过这一点扩展UiApplication{类func共享() - >UIAPPLICATION{返回uiapplication.shared}}
,但我得到了一个错误Function produces expected type 'UIApplication'; did you mean to call it with '()'?
。添加这些牙套会给我一个无限的循环。
即使我以某种方式获得了实例,我也无法理解如何调用
open
方法。让Selector = NSSelectorFromString('open(_:options:postion handhandler:)")让method =对象?.method(用于:选择器)方法(destinationurl,字符串:任何,nil)
最后一行给我Cannot call value of non-function type 'IMP'
。当按下Apple文档中的类型时,什么也不会发生。我找不到IMP
的描述以及如何使用它。
您可能会说:&quot"只是将Require only app-extension-safe api
设置为扩展名的设置中的NO
,并正常致电UIApplication.shared
。我要回答说,我的构建物被iTunes Connect
拒绝了Compliance with export requirements is required
或类似的内容(当我的整个OS使用英语时,iTunes Connect在俄语中)。
所以这是:
- 有没有办法在
Swift
中使用ASCII代码获得UIApplication.shared
?
顺便说一句,我得到了
的班级名称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) ?? ""
- 如何调用具有
IMP
类型的方法?
非常感谢。
问题是,您不应该首先尝试从扩展名访问sharedApplication
。
根据应用程序扩展程序指南:
某些API不可用应用程序扩展
由于其在系统中的重点作用,应用程序扩展不符合参与某些活动的资格。应用扩展不能:
- 访问共享应用对象,因此无法使用该对象上的任何方法
因此,您可能会破解它,但这将导致您的申请在审核时被拒绝。
但是,要执行您尝试做的事情(打开一个URL),您不需要sharedApplication
-您只需使用NSExtensionContext
s打开(_:pleastionHandler:)
extensionContext.open(myUrl, completionHandler: myCompletionHandler)
尽管.shared
属性在扩展中不可直接可用,但您可以通过#keyPath
访问它:
let application = UIApplication.value(forKeyPath: #keyPath(UIApplication.shared)) as! UIApplication