iOS Share Extension之自定義界面

一切源于開發(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了

屏幕快照 2018-07-10 14.20.23.png

然后填入extension的名字悄但,我這里叫Share,點雞finish叹括,彈窗activate一下就可以了算墨。
分組.png

選中新的Target,把App Group打開一下汁雷,配置一下净嘀,名字就是group.你的hostapp的bundle.剛才起的名字。在host app里也要打開App Group侠讯。
屏幕快照 2018-07-10 15.40.45.png

編碼

創(chuàng)建完畢以后可以看到有一個默認的ShareViewController挖藏,頭文件繼承了系統(tǒng)的SLComposeServiceViewController,我們自定義的就不需要它了厢漩,刪不刪隨便膜眠。

屏幕快照 2018-07-10 14.32.29.png

在Share文件夾下新建一個控制器,繼承UIViewcontroller就行溜嗜,我這里叫CustomShareViewController宵膨。然后在這里的info.plist里,把新建的控制器加進去炸宵。把原先(上面)的鍵值換成新(下面)的辟躏。
分組.png

搭建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ù)

界面顯示弄好了,接下來就是cancelsave兩個按鈕的點擊事件了稚虎。注意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é)個樣幾:


屏幕快照 2018-07-10 15.55.21.png

再見寻拂。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末程奠,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子祭钉,更是在濱河造成了極大的恐慌瞄沙,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件慌核,死亡現(xiàn)場離奇詭異距境,居然都是意外死亡,警方通過查閱死者的電腦和手機垮卓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門垫桂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人扒接,你說我怎么就攤上這事伪货∶茄茫” “怎么了?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵碱呼,是天一觀的道長蒙挑。 經(jīng)常有香客問我,道長愚臀,這世上最難降的妖魔是什么忆蚀? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮姑裂,結(jié)果婚禮上馋袜,老公的妹妹穿的比我還像新娘。我一直安慰自己舶斧,他們只是感情好欣鳖,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著茴厉,像睡著了一般泽台。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上矾缓,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天怀酷,我揣著相機與錄音,去河邊找鬼嗜闻。 笑死蜕依,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的琉雳。 我是一名探鬼主播样眠,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼咐吼!你這毒婦竟也來了吹缔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤锯茄,失蹤者是張志新(化名)和其女友劉穎厢塘,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體肌幽,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡晚碾,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了喂急。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片格嘁。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖廊移,靈堂內(nèi)的尸體忽然破棺而出糕簿,到底是詐尸還是另有隱情探入,我是刑警寧澤,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布懂诗,位于F島的核電站蜂嗽,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏殃恒。R本人自食惡果不足惜植旧,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望离唐。 院中可真熱鬧病附,春花似錦、人聲如沸亥鬓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嵌戈。三九已至丽焊,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間咕别,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工写穴, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留惰拱,地道東北人。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓啊送,卻偏偏與公主長得像偿短,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子馋没,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

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