Share Extension - 自定义界面,上传相册文件

一、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

三、在相册的效果图

image.png

四、在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谢谢~~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容