我是靠谱客的博主 苗条服饰,最近开发中收集的这篇文章主要介绍iOS开发 ShareExtension文件分享,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

话不多说,直接干!

搭建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.imagepublic.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/envoyevy
application/fractalsfif
application/futuresplashspl
application/htahta
application/internet-property-streamacx
application/mac-binhex40hqx
application/msworddoc
application/msworddot
application/octet-stream*
application/octet-streambin
application/octet-streamclass
application/octet-streamdms
application/octet-streamexe
application/octet-streamlha
application/octet-streamlzh
application/odaoda
application/olescriptaxs
application/pdfpdf
application/pics-rulesprf
application/pkcs10p10
application/pkix-crlcrl
application/postscriptai
application/postscripteps
application/postscriptps
application/rtfrtf
application/set-payment-initiationsetpay
application/set-registration-initiationsetreg
application/vnd.ms-excelxla
application/vnd.ms-excelxlc
application/vnd.ms-excelxlm
application/vnd.ms-excelxls
application/vnd.ms-excelxlt
application/vnd.ms-excelxlw
application/vnd.ms-outlookmsg
application/vnd.ms-pkicertstoresst
application/vnd.ms-pkiseccatcat
application/vnd.ms-pkistlstl
application/vnd.ms-powerpointpot
application/vnd.ms-powerpointpps
application/vnd.ms-powerpointppt
application/vnd.ms-projectmpp
application/vnd.ms-workswcm
application/vnd.ms-workswdb
application/vnd.ms-workswks
application/vnd.ms-workswps
application/winhlphlp
application/x-bcpiobcpio
application/x-cdfcdf
application/x-compressz
application/x-compressedtgz
application/x-cpiocpio
application/x-cshcsh
application/x-directordcr
application/x-directordir
application/x-directordxr
application/x-dvidvi
application/x-gtargtar
application/x-gzipgz
application/x-hdfhdf
application/x-internet-signupins
application/x-internet-signupisp
application/x-iphoneiii
application/x-javascriptjs
application/x-latexlatex
application/x-msaccessmdb
application/x-mscardfilecrd
application/x-msclipclp
application/x-msdownloaddll
application/x-msmediaviewm13
application/x-msmediaviewm14
application/x-msmediaviewmvb
application/x-msmetafilewmf
application/x-msmoneymny
application/x-mspublisherpub
application/x-msschedulescd
application/x-msterminaltrm
application/x-mswritewri
application/x-netcdfcdf
application/x-netcdfnc
application/x-perfmonpma
application/x-perfmonpmc
application/x-perfmonpml
application/x-perfmonpmr
application/x-perfmonpmw
application/x-pkcs12p12
application/x-pkcs12pfx
application/x-pkcs7-certificatesp7b
application/x-pkcs7-certificatesspc
application/x-pkcs7-certreqrespp7r
application/x-pkcs7-mimep7c
application/x-pkcs7-mimep7m
application/x-pkcs7-signaturep7s
application/x-shsh
application/x-sharshar
application/x-shockwave-flashswf
application/x-stuffitsit
application/x-sv4cpiosv4cpio
application/x-sv4crcsv4crc
application/x-tartar
application/x-tcltcl
application/x-textex
application/x-texinfotexi
application/x-texinfotexinfo
application/x-troffroff
application/x-trofft
application/x-trofftr
application/x-troff-manman
application/x-troff-meme
application/x-troff-msms
application/x-ustarustar
application/x-wais-sourcesrc
application/x-x509-ca-certcer
application/x-x509-ca-certcrt
application/x-x509-ca-certder
application/ynd.ms-pkipkopko
application/zipzip
audio/basicau
audio/basicsnd
audio/midmid
audio/midrmi
audio/mpegmp3
audio/x-aiffaif
audio/x-aiffaifc
audio/x-aiffaiff
audio/x-mpegurlm3u
audio/x-pn-realaudiora
audio/x-pn-realaudioram
audio/x-wavwav
image/bmpbmp
image/cis-codcod
image/gifgif
image/iefief
image/jpegjpe
image/jpegjpeg
image/jpegjpg
image/pipegjfif
image/svg+xmlsvg
image/tifftif
image/tifftiff
image/x-cmu-rasterras
image/x-cmxcmx
image/x-iconico
image/x-portable-anymappnm
image/x-portable-bitmappbm
image/x-portable-graymappgm
image/x-portable-pixmapppm
image/x-rgbrgb
image/x-xbitmapxbm
image/x-xpixmapxpm
image/x-xwindowdumpxwd
message/rfc822mht
message/rfc822mhtml
message/rfc822nws
text/csscss
text/h323323
text/htmlhtm
text/htmlhtml
text/htmlstm
text/iulsuls
text/plainbas
text/plainc
text/plainh
text/plaintxt
text/richtextrtx
text/scriptletsct
text/tab-separated-valuestsv
text/webviewhtmlhtt
text/x-componenthtc
text/x-setextetx
text/x-vcardvcf
video/mpegmp2
video/mpegmpa
video/mpegmpe
video/mpegmpeg
video/mpegmpg
video/mpegmpv2
video/quicktimemov
video/quicktimeqt
video/x-la-asflsf
video/x-la-asflsx
video/x-ms-asfasf
video/x-ms-asfasr
video/x-ms-asfasx
video/x-msvideoavi
video/x-sgi-moviemovie
x-world/x-vrmlflr
x-world/x-vrmlvrml
x-world/x-vrmlwrl
x-world/x-vrmlwrz
x-world/x-vrmlxaf
x-world/x-vrmlxof

最后

以上就是苗条服饰为你收集整理的iOS开发 ShareExtension文件分享的全部内容,希望文章能够帮你解决iOS开发 ShareExtension文件分享所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部