一切源于開發(fā)的時候被提了個需求傀缩,從Photo提取圖片到app內(nèi)的時候柒爵,分享頁面右上角的"post"要求改成"save"根悼,查了一遍發(fā)現(xiàn)用系統(tǒng)的改不了文字批糟,所以只能自定義格了。
先提綱挈領(lǐng)一下:
- 不要使用
[UIScreen mainScreen].bounds
方法。 - 也不要使用外面寫的一些工具類徽鼎。
- 注意
NSUserDefault
的使用盛末,要使用[[NSUserDefaults alloc] initWithSuiteName:@"group.com.xx.oo.Share"]
。
創(chuàng)建extension
File -> New -> Target否淤,選中share extension就可以創(chuàng)建一個新的target了
然后填入extension的名字悄但,我這里叫
Share
,點雞finish叹括,彈窗activate一下就可以了算墨。選中新的Target,把App Group打開一下汁雷,配置一下净嘀,名字就是
group.你的hostapp的bundle.剛才起的名字
。在host app里也要打開App Group侠讯。編碼
創(chuàng)建完畢以后可以看到有一個默認的ShareViewController
挖藏,頭文件繼承了系統(tǒng)的SLComposeServiceViewController
,我們自定義的就不需要它了厢漩,刪不刪隨便膜眠。
在Share文件夾下新建一個控制器,繼承UIViewcontroller就行溜嗜,我這里叫
CustomShareViewController
宵膨。然后在這里的info.plist
里,把新建的控制器加進去炸宵。把原先(上面)的鍵值換成新(下面)的辟躏。搭建UI
在Controller里,創(chuàng)建想要的UI土全。
我這里以獲取Photo照片庫的圖片數(shù)據(jù)為例捎琐。
不要使用[UIScreen mainScreen].bounds
方法会涎,我被坑了好久??。
不要使用[UIScreen mainScreen].bounds
方法瑞凑,我被坑了好久??末秃。
不要使用[UIScreen mainScreen].bounds
方法,我被坑了好久??籽御。
也不要使用外面寫的一些工具類练慕。
也不要使用外面寫的一些工具類。
也不要使用外面寫的一些工具類技掏。
- (void)viewDidLoad {
[super viewDidLoad];
[self prepareUI];
//[self setUpData];
}
- (void)prepareUI {
UIImageView *container = [[UIImageView alloc] initWithFrame:CGRectMake(container_x, (self.view.frame.size.height - container_height*1.5) / 2, self.view.frame.size.width - 2 * container_x, container_height)];
container.layer.cornerRadius = 7.f;
container.layer.borderColor = [UIColor lightGrayColor].CGColor;
container.layer.borderWidth = 1.f;
container.layer.masksToBounds = YES;
container.backgroundColor = [UIColor whiteColor];
container.userInteractionEnabled = YES;
container.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin;
[self.view addSubview:_container = container];
UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[cancelBtn setTitle:@"Cancel" forState:UIControlStateNormal];
cancelBtn.frame = CGRectMake(margin, 0, cancel_width, cancel_height);
[cancelBtn addTarget:self action:@selector(cancelBtnClickHandler:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:cancelBtn];
UIButton *postBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[postBtn setTitle:@"Save" forState:UIControlStateNormal];
postBtn.frame = CGRectMake(container.frame.size.width - margin - cancel_width, 0, cancel_width, cancel_height);
[postBtn addTarget:self action:@selector(postBtnClickHandler:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:postBtn];
CGFloat y = CGRectGetMaxY(cancelBtn.frame) + margin;
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(container.frame.size.width - margin - thumb_w, cancel_height + margin, thumb_w, thumb_w)];
imgV.contentMode = UIViewContentModeScaleAspectFill;
imgV.clipsToBounds = YES;
[container addSubview:_thumbView = imgV];
UITextView *txtV = [[UITextView alloc] initWithFrame:CGRectMake(margin, y, container.frame.size.width - 3*margin - thumb_w, container.frame.size.height - y)];
txtV.font = [UIFont systemFontOfSize:15.f];
txtV.backgroundColor = [UIColor clearColor];
[container addSubview:_contentView = txtV];
}
界面就是普通打法贺待,在尺寸布局計算的時候如果用到了外面的一些分類或者mainScreen.bounds
那個方法,會拿不到尺寸零截,然后界面顯示不出來。
界面搭好了秃臣,就獲取一下數(shù)據(jù)涧衙。
獲取和展示數(shù)據(jù)
主要是通過Controller的extensionContext
屬性的inputItems
去獲取,獲取到以后該顯示顯示奥此,該賦值賦值弧哎。
- (void)setUpData {
[self.exportDatas removeAllObjects];
NSString *suitName = @"group.com.xx.oo.Share";
__weak typeof(self)weakSelf = self;
[self.extensionContext.inputItems enumerateObjectsUsingBlock:^(NSExtensionItem * _Nonnull extItem, NSUInteger idx, BOOL * _Nonnull stop) {
[extItem.attachments enumerateObjectsUsingBlock:^(NSItemProvider * _Nonnull itemProvider, NSUInteger idx, BOOL * _Nonnull stop) {
if ([itemProvider hasItemConformingToTypeIdentifier:@"public.image"]) {
[itemProvider loadItemForTypeIdentifier:@"public.image"
options:nil
completionHandler:^(id<NSSecureCoding> _Nullable item, NSError * _Null_unspecified error) {
if ([(NSObject *)item isKindOfClass:[NSURL class]]) {
weakSelf.item = item;
NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:suitName];
NSURL *fileURL = [groupURL URLByAppendingPathComponent:@"incomingShared"];
weakSelf.writeURL = fileURL;
NSData *existData = [[NSData alloc ]initWithContentsOfURL:fileURL];
NSMutableArray *exists = [NSMutableArray array];
if (existData) {
exists = [NSKeyedUnarchiver unarchiveObjectWithData:existData];
}
NSData *imageData = [[NSData alloc]initWithContentsOfURL:(NSURL*)item];
weakSelf.thumbView.image = [UIImage imageWithData:imageData];
weakSelf.imgDt = imageData;
weakSelf.extItem = extItem;
}
}];
weakSelf.hasExistsUrl = YES;
*stop = YES;
}
}];
if (weakSelf.hasExistsUrl) {
*stop = YES;
}
}];
}
取消和保存數(shù)據(jù)
界面顯示弄好了,接下來就是cancel
和save
兩個按鈕的點擊事件了稚虎。注意NSUserDefault
的使用撤嫩,要使用[[NSUserDefaults alloc] initWithSuiteName:@"group.com.xx.oo.Share"]
。
核心方法是[self.extensionContext cancelRequestWithError:]
和[self.extensionContext completeRequestReturningItems: completionHandler:]
第二個方法里把你需要的數(shù)據(jù)放到沙盒里蠢终,這樣host app就可以訪問了序攘。
- (void)cancelBtnClickHandler:(UIButton *)sender {
[self.extensionContext cancelRequestWithError:[NSError errorWithDomain:@"CustomShareError" code:NSUserCancelledError userInfo:nil]];
}
- (void)postBtnClickHandler:(UIButton *)sender {
if (!self.hasExistsUrl) {
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
return;
}
UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicatorView.frame = CGRectMake((self.view.frame.size.width - activityIndicatorView.frame.size.width) / 2,
(self.view.frame.size.height - activityIndicatorView.frame.size.height) / 2,
activityIndicatorView.frame.size.width,
activityIndicatorView.frame.size.height);
activityIndicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[self.view addSubview:activityIndicatorView];
//激活加載動畫
[activityIndicatorView startAnimating];
NSString *suitName = @"group.com.xx.oo.Share";
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:suitName];
[userDefaults setValue:((NSURL *)self.item).absoluteString forKey:@"share-image"];
//用于標記是新的分享
[userDefaults setBool:YES forKey:@"has-new-share"];
NSDictionary *dict = @{@"text":self.contentView.text,@"image":self.imgDt};
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@[dict]];
//寫入文件
[data writeToURL:self.writeURL atomically:YES];
[userDefaults synchronize];
[self.extensionContext completeRequestReturningItems:@[self.extItem] completionHandler:^(BOOL expired) {
[activityIndicatorView stopAnimating];
}];
}
host app獲取數(shù)據(jù)
在AppDelegate
的- applicationDidBecomeActive:
方法里拿到數(shù)據(jù)。
- (void)applicationDidBecomeActive:(UIApplication *)application {
//獲取共享的UserDefaults
NSString *suitName = @"group.com.xx.oo.Share";
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:suitName];
if ([userDefaults boolForKey:@"has-new-share"]){
//獲取分組的共享目錄
NSURL *groupURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:suitName];
NSURL *fileURL = [groupURL URLByAppendingPathComponent:@"incomingShared"];
NSData *dictData = [[NSData alloc ]initWithContentsOfURL:fileURL];
NSMutableArray *dicts = [NSKeyedUnarchiver unarchiveObjectWithData:dictData];
//讀取文件
for (NSDictionary *dict in dicts) {
UIImage * image = [[UIImage alloc]initWithData:dict[@"image"]];
NSString *name = dict[@"text"];
//拿到數(shù)據(jù)了哈哈后
}
[[NSFileManager defaultManager]removeItemAtURL:fileURL error:NULL];
//重置分享標識
[userDefaults setBool:NO forKey:@"has-new-share"];
}
}
結(jié)果是節(jié)個樣幾:
再見寻拂。