这里主要讲利用分享扩展(share extension
)实现系统分享到自己app的功能,扩展里面跳转宿主app,及数据传输等
创建成功会生成一个文件夹
info.plist
里面有激活扩展的规则,匹配规则会在系统分享里面出现自己的app。
NSExtensionActivationRule
:默认为字符串“TRUEPREDICATE”,表示在分享菜单中一直显示该扩展。生产环境不可用,必须将类型改为Dictionary类型,然后添加以下字段:
NSExtensionActivationSupportsAttachmentsWithMaxCount
附件包括File、Image和Movie三大类,单一、混选总量不超过指定数量
NSExtensionActivationSupportsAttachmentsWithMinCount
附件最少限制,当设置上面字段最多时生效,默认至少选择1个附件,分享菜单中才显示扩展插件图标。
NSExtensionActivationSupportsImageWithMaxCount
图片最多限制,单一、混选均不超过指定数量。
NSExtensionActivationSupportsMovieWithMaxCount
视频最多限制,单一、混选均不超过指定数量。
NSExtensionActivationSupportsText
是否支持文本类型,布尔类型,默认不支持。如【备忘录】的分享
NSExtensionActivationSupportsWebPageWithMaxCount
Web页面最多限制,为数值类型。默认不支持Web页面分享,需要自己设置一个数值。
NSExtensionActivationSupportsWebURLWithMaxCount
Web链接最多限制,为数值类型。默认不支持分享超链接,需要自己设置一个数值。
默认分享扩展类ShareViewController,自带视图,可以全部自定义,这里不讲诉
dispatch_group_t group = dispatch_group_create();
NSExtensionItem *extensionItem = self.extensionContext.inputItems[0];
for (NSItemProvider *attachment in extensionItem.attachments) {
if ([attachment hasItemConformingToTypeIdentifier:(NSString *)kUTTypeImage]) {
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[attachment loadItemForTypeIdentifier:(NSString *)kUTTypeImage
options:nil
completionHandler:^(id<NSSecureCoding> _Nullable item, NSError * _Null_unspecified error) {
NSData *data = [[NSData alloc]initWithContentsOfURL:item];
dispatch_group_leave(group);
}];
});
}
if ([attachment hasItemConformingToTypeIdentifier:(NSString *)kUTTypeMovie]) {
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[attachment loadItemForTypeIdentifier:(NSString *)kUTTypeMovie
options:nil
completionHandler:^(id<NSSecureCoding> _Nullable item, NSError * _Null_unspecified error) {
NSData *data = [[NSData alloc]initWithContentsOfURL:item];
dispatch_group_leave(group);
}];
});
}
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
UIResponder* responder =self;
responder = [responder nextResponder];
while((responder = [responder nextResponder]) !=nil) {
if([responder respondsToSelector:@selector(openURL:)] ==YES) {
//打开APP
//这里的asancloud是app的URL Schemes ,home是自己随便定义的,用于判断
[responder performSelector:@selector(openURL:) withObject:[NSURL URLWithString:[NSString stringWithFormat:@"custome://"]]];
//执行分享内容处理
[self.extensionContext completeRequestReturningItems:@[] completionHandler:NULL];
}
}
});
跳转宿主app后在一下方法中处理逻辑
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options;
首先要配置相同的 App Groups,必须group.开头
NSUserDefaults *de = [[NSUserDefaults alloc]initWithSuiteName:@"group.(跟上面app groups一致)"];
[de setObject:value forKey:@"key"];
宿主app 获取数据
NSUserDefaults *de = [[NSUserDefaults alloc]initWithSuiteName:@"group.(跟上面app groups一致)"];
id value = [de objectForKey:@"key"];
扩展要选择对应宿主app运行,但扩展属于独立进程,调试的时候运行扩展,宿主app里面的断点不会走,同样运行宿主app,扩展里面的断点不会执行