在没有用户界面的情况下(在这种情况下,扩展的类是 NSObject 的子类),我从未管理过完成处理程序以正常工作。
尽管有[itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeURL]
回报YES
,但在设备或模拟器上都不会调用 completionHandler。
在尝试了不同的方法后,我最终找到了基于 javascript 将 URL 传递回扩展的解决方法(抱歉,我在示例中使用的是 ObjC 而不是 Swift)。
Info.plist
NSExtension 部分:
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<dict>
<key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
<integer>1</integer>
</dict>
<key>NSExtensionJavaScriptPreprocessingFile</key>
<string>Action</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.services</string>
<key>NSExtensionPrincipalClass</key>
<string>ActionRequestHandler</string>
</dict>
JavascriptAction.js
文件:
var Action = function() {};
Action.prototype = {
run: function(arguments) {
arguments.completionFunction({ "currentURL" : window.location.href })
},
finalize: function(arguments) {
}
};
var ExtensionPreprocessingJS = new Action
ActionRequestHandler.h
头文件:
@interface ActionRequestHandler : NSObject <NSExtensionRequestHandling>
@end
ActionRequestHandler.m
基于默认的动作扩展模板:
#import "ActionRequestHandler.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface ActionRequestHandler ()
@property (nonatomic, strong) NSExtensionContext *extensionContext;
@end
@implementation ActionRequestHandler
- (void)beginRequestWithExtensionContext:(NSExtensionContext *)context {
// Do not call super in an Action extension with no user interface
self.extensionContext = context;
BOOL found = NO;
// Find the item containing the results from the JavaScript preprocessing.
for (NSExtensionItem *item in self.extensionContext.inputItems) {
for (NSItemProvider *itemProvider in item.attachments) {
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList options:nil completionHandler:^(NSDictionary *dictionary, NSError *error) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self itemLoadCompletedWithPreprocessingResults:dictionary[NSExtensionJavaScriptPreprocessingResultsKey]];
}];
}];
found = YES;
}
break;
}
if (found) {
break;
}
}
if (!found) {
// We did not find anything - signal that we're done
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
// Don't hold on to this after we finished with it
self.extensionContext = nil;
}
}
- (void)itemLoadCompletedWithPreprocessingResults:(NSDictionary *)javaScriptPreprocessingResults
{
// Get the URL
if ([javaScriptPreprocessingResults[@"currentURL"] length] != 0) {
NSLog(@"*** URL: %@", javaScriptPreprocessingResults[@"currentURL"]);
}
// Signal that we're done
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
// Don't hold on to this after we finished with it
self.extensionContext = nil;
}
@end
希望它能帮助人们节省几个小时在完成处理程序问题上的挣扎。