Share Extension - 自定義界面照雁,上傳相冊文件

一蚕愤、share extension的相關(guān)設(shè)置

這里我也就不多寫這些相關(guān)設(shè)置了,因?yàn)橐徽铱梢哉业揭淮蟀选?/p>

二饺蚊,自定義界面以及文件類型判斷

//

//  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];



    /**設(shè)定間距**/

    //與top和bottom的間距

    CGFloattopSpacing =80;

    //與left和right的間距

    CGFloatleftSpacing =15;

    //按鈕的高度

    CGFloatviewHeight =40;

    //定義一個容器視圖來存放分享內(nèi)容和兩個操作按鈕

    _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項(xiàng)",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;//設(shè)置Pagecontroller的頁數(shù)

    _pgControler.currentPage = 0;//設(shè)置Pagecontroller的當(dāng)前頁

    _pgControler.pageIndicatorTintColor = ASAuxiliaryColor;

    _pgControler.currentPageIndicatorTintColor = ASMianColor;

    [_containerView addSubview:_pgControler];



    views = [[NSMutableArray alloc]init];

    //獲取所有選項(xiàng)

    __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);

    }];

}

//加載圖片預(yù)覽

- (void)addScrollerView

{

    _sView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 55,_containerView.frame.size.width, _containerView.frame.size.height - 2*40 - 55)];

    //必須設(shè)置contentSize审胸,要不然滾動不了(scrollEnabled默認(rèn)為YES,可以滾動)

    _sView.contentSize = CGSizeMake(_sView.frame.size.width * views.count, 0);

    //設(shè)置翻頁效果

    _sView.pagingEnabled = YES;

    //啟動時候設(shè)置偏移量顯示數(shù)組中的第二張圖

    _sView.contentOffset = CGPointMake(0, 0);

    //設(shè)置代理

    _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;

    //獲取所有選項(xiàng)

    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:@""];

                }

            }];

        }

    }

}

// 將文件復(fù)制到 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 否則會出現(xiàn)APP無法調(diào)起來的情況

 **/

- (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]]]];

            //執(zhí)行分享內(nèi)容處理

            [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(@"第三方進(jìn)來:%@", 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調(diào)起的情況

-(BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url{

    // 交給微信處理,如果它能處理 會回調(diào)delegate的相關(guān)方法如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];

這樣就可以獲取文件內(nèi)容。

第一次寫挤渐,如果有錯誤的地方或不妥之處請大家指正苹享,以免誤導(dǎo)更多人。謝謝O(∩_∩)O謝謝~~~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市得问,隨后出現(xiàn)的幾起案子囤攀,更是在濱河造成了極大的恐慌,老刑警劉巖宫纬,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件焚挠,死亡現(xiàn)場離奇詭異,居然都是意外死亡漓骚,警方通過查閱死者的電腦和手機(jī)蝌衔,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蝌蹂,“玉大人噩斟,你說我怎么就攤上這事」赂觯” “怎么了剃允?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長硼身。 經(jīng)常有香客問我硅急,道長,這世上最難降的妖魔是什么佳遂? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任营袜,我火速辦了婚禮,結(jié)果婚禮上丑罪,老公的妹妹穿的比我還像新娘荚板。我一直安慰自己,他們只是感情好吩屹,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布跪另。 她就那樣靜靜地躺著,像睡著了一般煤搜。 火紅的嫁衣襯著肌膚如雪免绿。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天擦盾,我揣著相機(jī)與錄音嘲驾,去河邊找鬼。 笑死迹卢,一個胖子當(dāng)著我的面吹牛辽故,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播腐碱,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼誊垢,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起喂走,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤殃饿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后缴啡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體壁晒,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡瓷们,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年业栅,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谬晕。...
    茶點(diǎn)故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡碘裕,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出攒钳,到底是詐尸還是另有隱情帮孔,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布不撑,位于F島的核電站文兢,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏焕檬。R本人自食惡果不足惜姆坚,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望实愚。 院中可真熱鬧兼呵,春花似錦、人聲如沸腊敲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽碰辅。三九已至懂昂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間没宾,已是汗流浹背凌彬。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留榕吼,地道東北人饿序。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像羹蚣,于是被迫代替她去往敵國和親原探。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容