概述
话不多说,直接干!
搭建ShareExtension
自定义UI,创建一个继承于UIViewController的类。
如果发布App StoreNSExtensionActivationRule
必须配置一下,否则Apple会拒绝的。官方规则
布局UI的时候,切记不用使用UIApplication和[UIScreen mainScreen]做什么事情,你拿不到这些数据,使用self.view.frame即可
布局UI的时候,切记不用使用UIApplication和[UIScreen mainScreen]做什么事情,你拿不到这些数据,使用self.view.frame即可
布局UI的时候,切记不用使用UIApplication和[UIScreen mainScreen]做什么事情,你拿不到这些数据,使用self.view.frame即可
获取数据
//exportDatas:可变数组
- (void)setUpData {
[self.exportDatas removeAllObjects];
[self.extensionContext.inputItems enumerateObjectsUsingBlock:^(NSExtensionItem * _Nonnull extItem, NSUInteger idx, BOOL * _Nonnull stop) {
[extItem.attachments enumerateObjectsUsingBlock:^(NSItemProvider * _Nonnull itemProvider, NSUInteger idx, BOOL * _Nonnull stop) {
[self.exportDatas addObject:itemProvider];
if (![itemProvider hasItemConformingToTypeIdentifier:@"public.image"]) {
self.isOnlyImages = NO;
} //@"public.movie"视频//@"public.file-url"文件//@"public.url"url连接//@"public.plain-text"文字
}];
}];
[self loadItemForTypeIdentifier];
}
展示的代码,我把自己的UI处理和相关逻辑去掉了(规避一下,不懂的可以评论或私信我), loadItemForTypeIdentifier
是异步任务,注意回到主线程处理UI,
- (void)loadItemForTypeIdentifier {
CGFloat scrViewWidth = self.contentScrView.frame.size.width;
__weak typeof(self)weakSelf = self;
if (self.isOnlyImages) { //只有图片 横向排列
for (NSItemProvider *itemProvider in self.exportDatas) {
[itemProvider loadItemForTypeIdentifier:@"public.image"
options:nil
completionHandler:^(id<NSSecureCoding> _Nullable item, NSError * _Null_unspecified error) {
if ([(NSObject *)item isKindOfClass:[NSURL class]]) {
NSData *imageData = [[NSData alloc]initWithContentsOfURL:(NSURL*)item];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
//UI布局
});
}
}];
}
} else { //竖向排列
for (int i = 0; i < self.exportDatas.count; i++) {
NSItemProvider *itemProvider = self.exportDatas[i];
[itemProvider loadItemForTypeIdentifier:@"public.data"
options:nil
completionHandler:^(id<NSSecureCoding> _Nullable item, NSError * _Null_unspecified error) {
//public.data 会解析所有数据,不能按image处理展示
}];
}
}
}
分享成功 和 取消分享
分享的话你得给用户关闭和上传按钮吧
//关闭
- (void)closeBtnClick {
[self.extensionContext cancelRequestWithError:[NSError errorWithDomain:@"用户取消" code:NSUserCancelledError userInfo:nil]];
}
上传数据使用Apple原生的就行,没必要再整个AFNetworking,做完你的业务调用completeRequestReturningItems
会关闭页面,这个时候你可以选择唤醒你的APP
[self.extensionContext completeRequestReturningItems:@[] completionHandler:^(BOOL expired) {
//唤醒hostAPP
// [self openAppWithURL:@"" text:@""];
}];
唤醒HostAPP
- (void)openAppWithURL:(NSString*)urlString text:(NSString*)text {
UIResponder* responder = self;
while ((responder = [responder nextResponder]) != nil) {
if ([responder respondsToSelector:@selector(openURL:)] == YES) {
[responder performSelector:@selector(openURL:) withObject:[NSURL URLWithString:[NSString stringWithFormat:@"wuwuFQ_shareExtension://%@", [self urlStringForShareExtension:urlString text:text]]]];
}
}
}
- (NSString*)urlStringForShareExtension:(NSString*)urlString text:(NSString*)text {
NSString *finalUrl = [NSString stringWithFormat:@"%@____%@", text, urlString];
finalUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)finalUrl, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
return finalUrl;
}
你的主APP的 AppDelegate
必须有且允许打开
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
if([[url absoluteString] hasPrefix:@"wuwuFQ_shareExtension"]) {
return YES;
}
return NO;
}
//API_AVAILABLE(ios(9.0));
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
if([[url absoluteString] hasPrefix:@"wuwuFQ_shareExtension"]) {
return YES;
}
return NO;
}
白嫖的知识 APP Groups
你不上传文件,只是用APP打开,那就要用到APP Groups
ShareExtension和主APP都要添加共用一个,用group.ShareExtension的Bundle Identifier命名就行。
ShareExtension生成共享数据
#pragma mark - NSUserDefaults
- (void)setAppGroup1
{
NSString *suitName = @"group.com.xxx.xxx.xxxShareExtension";
NSUserDefaults *myDefaults = [[NSUserDefaults alloc] initWithSuiteName:suitName];
[myDefaults setObject:@"value" forKey:@"key"];
NSLog(@"%@", [myDefaults valueForKey:@"key"]);
}
#pragma mark - NSFileManager
- (void)setAppGroup2{
NSString *suitName = @"group.com.xxx.xxx.xxxShareExtension";
//获取分组的共享目录
NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:suitName];
NSURL *fileURL = [groupURL URLByAppendingPathComponent:@"demo.txt"];
//写入文件
[@"abc" writeToURL:fileURL atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
AppDelegate获取共享数据
#pragma mark - NSUserDefaults
- (void)getByAppGroup1
{
NSString *suitName = @"group.com.xxx.xxx.xxxShareExtension";
NSUserDefaults *myDefaults = [[NSUserDefaults alloc]initWithSuiteName:suitName];
NSString *content = [myDefaults objectForKey:@"key"];
NSLog(@"%@",content);
}
#pragma mark - NSFileManager
- (void)getByAppGroup2{
NSString *suitName = @"group.com.xxx.xxx.xxxShareExtension";
//获取分组的共享目录
NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:suitName];
NSURL *fileURL = [groupURL URLByAppendingPathComponent:@"demo.txt"];
//读取文件
NSString *str = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str = %@", str);
}
疑难杂点–获取文件类型
文件类型根据路径后缀去判断是不太准确的,后缀命名太多或没有后缀,网上有根据二进制的ascii码来进行判断的,周到的资料不太全,也看了SDWebImage的,SDWebImage只处理了Image相关的,其他文件类型还是没有办法,Apple官方的public.image
、public.text
等,感觉解析PDF、Word等类型还是比较麻烦。最终采用了C语言的解析方式。
引入#import <MobileCoreServices/MobileCoreServices.h>
MIME 参考手册
/// MIMEType获取文件类型
/// @param path 文件地址
- (NSString *)mimeTypeForFileAtPath:(NSString *)path
{
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
CFRelease(UTI);
if (!MIMEType) {
return @"application/octet-stream";
}
return (__bridge NSString *)(MIMEType);
}
按照内容类型排列的 Mime 类型列表
类型/子类型 | 扩展名 |
---|---|
application/envoy | evy |
application/fractals | fif |
application/futuresplash | spl |
application/hta | hta |
application/internet-property-stream | acx |
application/mac-binhex40 | hqx |
application/msword | doc |
application/msword | dot |
application/octet-stream | * |
application/octet-stream | bin |
application/octet-stream | class |
application/octet-stream | dms |
application/octet-stream | exe |
application/octet-stream | lha |
application/octet-stream | lzh |
application/oda | oda |
application/olescript | axs |
application/pdf | |
application/pics-rules | prf |
application/pkcs10 | p10 |
application/pkix-crl | crl |
application/postscript | ai |
application/postscript | eps |
application/postscript | ps |
application/rtf | rtf |
application/set-payment-initiation | setpay |
application/set-registration-initiation | setreg |
application/vnd.ms-excel | xla |
application/vnd.ms-excel | xlc |
application/vnd.ms-excel | xlm |
application/vnd.ms-excel | xls |
application/vnd.ms-excel | xlt |
application/vnd.ms-excel | xlw |
application/vnd.ms-outlook | msg |
application/vnd.ms-pkicertstore | sst |
application/vnd.ms-pkiseccat | cat |
application/vnd.ms-pkistl | stl |
application/vnd.ms-powerpoint | pot |
application/vnd.ms-powerpoint | pps |
application/vnd.ms-powerpoint | ppt |
application/vnd.ms-project | mpp |
application/vnd.ms-works | wcm |
application/vnd.ms-works | wdb |
application/vnd.ms-works | wks |
application/vnd.ms-works | wps |
application/winhlp | hlp |
application/x-bcpio | bcpio |
application/x-cdf | cdf |
application/x-compress | z |
application/x-compressed | tgz |
application/x-cpio | cpio |
application/x-csh | csh |
application/x-director | dcr |
application/x-director | dir |
application/x-director | dxr |
application/x-dvi | dvi |
application/x-gtar | gtar |
application/x-gzip | gz |
application/x-hdf | hdf |
application/x-internet-signup | ins |
application/x-internet-signup | isp |
application/x-iphone | iii |
application/x-javascript | js |
application/x-latex | latex |
application/x-msaccess | mdb |
application/x-mscardfile | crd |
application/x-msclip | clp |
application/x-msdownload | dll |
application/x-msmediaview | m13 |
application/x-msmediaview | m14 |
application/x-msmediaview | mvb |
application/x-msmetafile | wmf |
application/x-msmoney | mny |
application/x-mspublisher | pub |
application/x-msschedule | scd |
application/x-msterminal | trm |
application/x-mswrite | wri |
application/x-netcdf | cdf |
application/x-netcdf | nc |
application/x-perfmon | pma |
application/x-perfmon | pmc |
application/x-perfmon | pml |
application/x-perfmon | pmr |
application/x-perfmon | pmw |
application/x-pkcs12 | p12 |
application/x-pkcs12 | pfx |
application/x-pkcs7-certificates | p7b |
application/x-pkcs7-certificates | spc |
application/x-pkcs7-certreqresp | p7r |
application/x-pkcs7-mime | p7c |
application/x-pkcs7-mime | p7m |
application/x-pkcs7-signature | p7s |
application/x-sh | sh |
application/x-shar | shar |
application/x-shockwave-flash | swf |
application/x-stuffit | sit |
application/x-sv4cpio | sv4cpio |
application/x-sv4crc | sv4crc |
application/x-tar | tar |
application/x-tcl | tcl |
application/x-tex | tex |
application/x-texinfo | texi |
application/x-texinfo | texinfo |
application/x-troff | roff |
application/x-troff | t |
application/x-troff | tr |
application/x-troff-man | man |
application/x-troff-me | me |
application/x-troff-ms | ms |
application/x-ustar | ustar |
application/x-wais-source | src |
application/x-x509-ca-cert | cer |
application/x-x509-ca-cert | crt |
application/x-x509-ca-cert | der |
application/ynd.ms-pkipko | pko |
application/zip | zip |
audio/basic | au |
audio/basic | snd |
audio/mid | mid |
audio/mid | rmi |
audio/mpeg | mp3 |
audio/x-aiff | aif |
audio/x-aiff | aifc |
audio/x-aiff | aiff |
audio/x-mpegurl | m3u |
audio/x-pn-realaudio | ra |
audio/x-pn-realaudio | ram |
audio/x-wav | wav |
image/bmp | bmp |
image/cis-cod | cod |
image/gif | gif |
image/ief | ief |
image/jpeg | jpe |
image/jpeg | jpeg |
image/jpeg | jpg |
image/pipeg | jfif |
image/svg+xml | svg |
image/tiff | tif |
image/tiff | tiff |
image/x-cmu-raster | ras |
image/x-cmx | cmx |
image/x-icon | ico |
image/x-portable-anymap | pnm |
image/x-portable-bitmap | pbm |
image/x-portable-graymap | pgm |
image/x-portable-pixmap | ppm |
image/x-rgb | rgb |
image/x-xbitmap | xbm |
image/x-xpixmap | xpm |
image/x-xwindowdump | xwd |
message/rfc822 | mht |
message/rfc822 | mhtml |
message/rfc822 | nws |
text/css | css |
text/h323 | 323 |
text/html | htm |
text/html | html |
text/html | stm |
text/iuls | uls |
text/plain | bas |
text/plain | c |
text/plain | h |
text/plain | txt |
text/richtext | rtx |
text/scriptlet | sct |
text/tab-separated-values | tsv |
text/webviewhtml | htt |
text/x-component | htc |
text/x-setext | etx |
text/x-vcard | vcf |
video/mpeg | mp2 |
video/mpeg | mpa |
video/mpeg | mpe |
video/mpeg | mpeg |
video/mpeg | mpg |
video/mpeg | mpv2 |
video/quicktime | mov |
video/quicktime | qt |
video/x-la-asf | lsf |
video/x-la-asf | lsx |
video/x-ms-asf | asf |
video/x-ms-asf | asr |
video/x-ms-asf | asx |
video/x-msvideo | avi |
video/x-sgi-movie | movie |
x-world/x-vrml | flr |
x-world/x-vrml | vrml |
x-world/x-vrml | wrl |
x-world/x-vrml | wrz |
x-world/x-vrml | xaf |
x-world/x-vrml | xof |
最后
以上就是苗条服饰为你收集整理的iOS开发 ShareExtension文件分享的全部内容,希望文章能够帮你解决iOS开发 ShareExtension文件分享所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复