一蚕愤、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謝謝~~~~