一、share extension的相关设置
这里我也就不多写这些相关设置了,因为一找可以找到一大把。
二,自定义界面以及文件类型判断
//
// CustomShareViewController.m
// Share
//
// Created by SyyiOSDev on 2017/12/22.
// Copyright © 2017年 jungle. All rights reserved.
//
/**主色**/
#define ASMianColor [self colorWithHexString:@"#3688ff"]
/**辅助色**/
#define ASAuxiliaryColor [self colorWithHexString:@"#c7deff"]
#import "CustomShareViewController.h"
#import
#import
@interface CustomShareViewController ()
{
UIScrollView*_sView;
UIPageControl*_pgControler;
NSMutableArray *views;
}
@property (nonatomic, strong) UIView *containerView;
@end
@implementationCustomShareViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addShareViewUI];
}
//自定义分享视图
- (void)addShareViewUI{
NSExtensionItem *extensionItem = self.extensionContext.inputItems.firstObject;
UIView *view = [[UIView alloc]initWithFrame:self.view.frame];
view.backgroundColor = [UIColor blackColor];
view.alpha=0.6;
[self.view addSubview:view];
/**设定间距**/
//与top和bottom的间距
CGFloattopSpacing =80;
//与left和right的间距
CGFloatleftSpacing =15;
//按钮的高度
CGFloatviewHeight =40;
//定义一个容器视图来存放分享内容和两个操作按钮
_containerView = [[UIView alloc] initWithFrame:CGRectMake(leftSpacing, self.view.frame.size.height, self.view.frame.size.width - 2*leftSpacing, self.view.frame.size.height - 2*topSpacing)];
_containerView.layer.cornerRadius = 7;
_containerView.layer.masksToBounds = YES;
_containerView.backgroundColor = [UIColor whiteColor];
_containerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[self.view addSubview:_containerView];
//定义Post和Cancel按钮
UIButton *cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 5, 70, viewHeight)];
[cancelBtnsetTitle:@"取消" forState:UIControlStateNormal];
[cancelBtnsetTitleColor:ASMianColor forState:UIControlStateNormal];
cancelBtn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
[cancelBtnaddTarget:self action:@selector(cancelBtnClickHandler:) forControlEvents:UIControlEventTouchUpInside];
[_containerViewaddSubview:cancelBtn];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((_containerView.frame.size.width - 100)/2, 5, 100, viewHeight)];
label.text = [NSString stringWithFormat:@"共%lu项",extensionItem.attachments.count];
label.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
label.textAlignment = NSTextAlignmentCenter;
[_containerView addSubview:label];
UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, viewHeight + 10, _containerView.frame.size.width, 1)];
line.backgroundColor = ASAuxiliaryColor;
[_containerView addSubview:line];
_pgControler = [[UIPageControl alloc]initWithFrame:CGRectMake((_containerView.frame.size.width - 100)/2, _containerView.frame.size.height - 70, 100, 10)];
_pgControler.numberOfPages = extensionItem.attachments.count;//设置Pagecontroller的页数
_pgControler.currentPage = 0;//设置Pagecontroller的当前页
_pgControler.pageIndicatorTintColor = ASAuxiliaryColor;
_pgControler.currentPageIndicatorTintColor = ASMianColor;
[_containerView addSubview:_pgControler];
views = [[NSMutableArray alloc]init];
//获取所有选项
__blockNSUIntegernumber =0;
for(NSItemProvider*providerinextensionItem.attachments) {
NSLog(@"attachments:%lu",extensionItem.attachments.count);
//判断是否是图片文件
if ([provider hasItemConformingToTypeIdentifier:(NSString *) kUTTypeImage]) {
[providerloadItemForTypeIdentifier:(NSString *) kUTTypeImage options:nil completionHandler:^(id _Nullable item,NSError * _Null_unspecified error) {
NSURL*imageUrl = (NSURL*)item;
//获取图片
UIImage *imageItem = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
[viewsaddObject:imageItem];
number ++ ;
if(number == extensionItem.attachments.count) {
[selfaddScrollerView];
}
}];
}
//判断是否是视频文件
if ([provider hasItemConformingToTypeIdentifier:(NSString *) kUTTypeMovie]) {
[providerloadItemForTypeIdentifier:(NSString *) kUTTypeMovie options:nil completionHandler:^(id _Nullable item, NSError * _Null_unspecified error) {
NSURL*videoUrl = (NSURL*)item;
//获取缩略图
UIImage*imageItem = [selfgetScreenShotImageFromVideoPath:videoUrl];
[viewsaddObject:imageItem];
number ++ ;
if(number == extensionItem.attachments.count) {
[selfaddScrollerView];
}
}];
}
}
UIButton *postBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[postBtnsetTitle:@"分享至阿山云智能存储NAS" forState:UIControlStateNormal];
postBtn.frame=CGRectMake(20,_containerView.frame.size.height- viewHeight -10,_containerView.frame.size.width-40, viewHeight);
[postBtnsetTitleColor:ASMianColor forState:UIControlStateNormal];
postBtn.backgroundColor = ASAuxiliaryColor;
postBtn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
postBtn.layer.cornerRadius = 20.0;
postBtn.layer.masksToBounds = YES;
[postBtnaddTarget:self action:@selector(postBtnClickHandler:) forControlEvents:UIControlEventTouchUpInside];
[_containerViewaddSubview:postBtn];
[UIView animateWithDuration:0.5 animations:^{
_containerView.frame=CGRectMake(leftSpacing, topSpacing,self.view.frame.size.width-2*leftSpacing,self.view.frame.size.height-2*topSpacing);
}];
}
//加载图片预览
- (void)addScrollerView
{
_sView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 55,_containerView.frame.size.width, _containerView.frame.size.height - 2*40 - 55)];
//必须设置contentSize,要不然滚动不了(scrollEnabled默认为YES,可以滚动)
_sView.contentSize = CGSizeMake(_sView.frame.size.width * views.count, 0);
//设置翻页效果
_sView.pagingEnabled = YES;
//启动时候设置偏移量显示数组中的第二张图
_sView.contentOffset = CGPointMake(0, 0);
//设置代理
_sView.delegate=self;
[_sView setShowsHorizontalScrollIndicator:NO];
[_containerView addSubview:_sView];
for(inti =0; i
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(_containerView.frame.size.width*i, 0, _containerView.frame.size.width, _sView.frame.size.height)];
[imgViewsetImage:views[i]];
imgView.clipsToBounds=YES;
imgView.contentMode = UIViewContentModeScaleAspectFill;
[_sViewaddSubview:imgView];
}
}
/**
* 获取视频的缩略图方法
*
* @param fileURL 视频的本地路径
*
* @return 视频截图
*/
- (UIImage*)getScreenShotImageFromVideoPath:(NSURL*)fileURL{
UIImage*shotImage;
//视频路径URL
// NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(1, 1);
NSError*error =nil;
CMTimeactualTime;
CGImageRefimage = [gencopyCGImageAtTime:timeactualTime:&actualTimeerror:&error];
shotImage = [[UIImagealloc]initWithCGImage:image];
CGImageRelease(image);
returnshotImage;
}
#pragma mark UIScrollViewDelegate
// scrollview 减速停止
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
_pgControler.currentPage = scrollView.contentOffset.x / _containerView.frame.size.width;
}
- (void)cancelBtnClickHandler:(id)sender
{
[self.extensionContext cancelRequestWithError:[NSError errorWithDomain:@"CustomShareError" code:NSUserCancelledError userInfo:nil]];
}
//确定处理
- (void)postBtnClickHandler:(id)sender
{
NSExtensionItem *extensionItem = self.extensionContext.inputItems.firstObject;
NSUserDefaults *myDefaults = [[NSUserDefaults alloc]
initWithSuiteName:@"group.ASanCloud.com"];
[myDefaultssetBool:YESforKey:@"has-new-share"];
__blockNSUIntegernumber =0;
//获取所有选项
for(NSItemProvider*providerinextensionItem.attachments) {
NSLog(@"attachments:%lu",extensionItem.attachments.count);
//判断是否是图片文件
if ([provider hasItemConformingToTypeIdentifier:(NSString *) kUTTypeImage]) {
[providerloadItemForTypeIdentifier:(NSString *) kUTTypeImage options:nil completionHandler:^(id _Nullable item,NSError * _Null_unspecified error) {
NSURL*imageUrl = (NSURL*)item;
[selfcopyResToAppGroup:imageUrl];
number ++ ;
if(number == extensionItem.attachments.count) {
[selfopenAppWithURL:@""text:@""];
}
}];
}
//判断是否是视频文件
if ([provider hasItemConformingToTypeIdentifier:(NSString *) kUTTypeMovie]) {
[providerloadItemForTypeIdentifier:(NSString *) kUTTypeMovie options:nil completionHandler:^(id _Nullable item, NSError * _Null_unspecified error) {
NSURL*videoUrl = (NSURL*)item;
[selfcopyResToAppGroup:videoUrl];
number ++ ;
if(number == extensionItem.attachments.count) {
[selfopenAppWithURL:@""text:@""];
}
}];
}
}
}
// 将文件复制到 app group
- (BOOL) copyResToAppGroup:(NSURL*) sorURL
{
NSError*error =nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *groupURL = [fileManager containerURLForSecurityApplicationGroupIdentifier:@"group.ASanCloud.com"];
groupURL = [groupURLURLByAppendingPathComponent:@"upload"];
BOOLisDir =NO;
if(![fileManagerfileExistsAtPath:groupURL.relativePathisDirectory:&isDir] && !isDir)
[fileManagercreateDirectoryAtURL:groupURL withIntermediateDirectories:YES attributes:nil error:&error];
NSString *name = [[sorURL lastPathComponent] stringByDeletingPathExtension];
NSString*ext = [sorURLpathExtension];
groupURL = [groupURLURLByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", name, ext]];
return[fileManagercopyItemAtURL:sorURLtoURL:groupURLerror:&error];
}
/**
*打开APP
*注:需要先走打开APP 再走self.extensionContext 否则会出现APP无法调起来的情况
**/
- (void)openAppWithURL:(NSString*)urlString text:(NSString*)text {
UIResponder* responder =self;
responder = [respondernextResponder];
while((responder = [respondernextResponder]) !=nil) {
if([responderrespondsToSelector:@selector(openURL:)] ==YES) {
//打开APP
//这里的asancloud是app的URL Schemes ,home是自己随便定义的,用于判断
[responderperformSelector:@selector(openURL:) withObject:[NSURL URLWithString:[NSString stringWithFormat:@"asancloud://%@home", [self urlStringForShareExtension:urlString text:text]]]];
//执行分享内容处理
[self.extensionContext completeRequestReturningItems:nil completionHandler:NULL];
}
}
}
- (NSString*)urlStringForShareExtension:(NSString*)urlString text:(NSString*)text {
NSString* finalUrl=[NSStringstringWithFormat:@"%@____%@", text, urlString];
finalUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)finalUrl,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8));
returnfinalUrl;
}
//颜色
- (UIColor*)colorWithHexString: (NSString*)color
{
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if([cStringlength] <6) {
return [UIColor clearColor];
}
// strip 0X if it appears
if([cStringhasPrefix:@"0X"])
cString = [cStringsubstringFromIndex:2];
if([cStringhasPrefix:@"#"])
cString = [cStringsubstringFromIndex:1];
if([cStringlength] !=6)
return [UIColor clearColor];
// Separate into r, g, b substrings
NSRangerange;
range.location=0;
range.length=2;
//r
NSString*rString = [cStringsubstringWithRange:range];
//g
range.location=2;
NSString*gString = [cStringsubstringWithRange:range];
//b
range.location=4;
NSString*bString = [cStringsubstringWithRange:range];
// Scan values
unsignedintr, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return[UIColorcolorWithRed:((float) r /255.0f)green:((float) g /255.0f)blue:((float) b /255.0f)alpha:1.0f];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
三、在相册的效果图
四、在Containing App中的一些操作
在AppDelegate中获取判断
- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary *)options
{
NSString *path = [url absoluteString];
path = [pathstringByRemovingPercentEncoding];
NSLog(@"第三方进来:%@", path);
//这里的asancloud是app的URL Schemes ,home是自己随便定义的,用于判断
if ([url.absoluteString hasPrefix:@"asancloud"]) {
//判断是否是从相册过来
if ([url.absoluteString hasSuffix:@"home"]) {//判断是否是直接跳入到添加页面
ASUploadingPathViewController *uploadVC = [[ASUploadingPathViewController alloc]init];
uploadVC.filePath=@"/";
[((UITabBarController *)self.window.rootViewController).selectedViewController pushViewController:uploadVC animated:YES];
}
}else if ([url.absoluteString hasPrefix:@"file:"]){
//判断是否从其他APP分享过来的文件
ASUploadingPathViewController *uploadVC = [[ASUploadingPathViewController alloc]init];
uploadVC.filePath=@"/";
uploadVC.fileContentPath= path;
[((UITabBarController *)self.window.rootViewController).selectedViewController pushViewController:uploadVC animated:YES];
}
return YES;
}
//处理其他app调起的情况
-(BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url{
// 交给微信处理,如果它能处理 会回调delegate的相关方法如onResp:
return [WXApi handleOpenURL:url delegate:self];
}
五、ASUploadingPathViewController是我这里上传的页面,也是对相册过来文件的处理页面
//获取分享沙盒里的文件
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *groupURL = [fileManager containerURLForSecurityApplicationGroupIdentifier:@"group.ASanCloud.com"];
groupURL = [groupURLURLByAppendingPathComponent:@"upload"];
NSString *dataPath = [groupURL.absoluteString substringFromIndex:15];
NSArray*array = [fileManagercontentsOfDirectoryAtPath:dataPatherror:nil];
NSLog(@"arrrrrr:%lu",(unsignedlong)array.count);
这里就可以获取到所有文件的路径地址了:NSData*data = [fileManagercontentsAtPath:fileDataPath];
这样就可以获取文件内容。
第一次写,如果有错误的地方或不妥之处请大家指正,以免误导更多人。谢谢O(∩_∩)O谢谢~~~~