美文网首页iOS开发讨论会
iOS Share Extension之自定义界面

iOS Share Extension之自定义界面

作者: 幂琪有天 | 来源:发表于2018-07-10 15:57 被阅读79次

一切源于开发的时候被提了个需求,从Photo提取图片到app内的时候,分享页面右上角的"post"要求改成"save",查了一遍发现用系统的改不了文字,所以只能自定义。
先提纲挈领一下:

  • 不要使用[UIScreen mainScreen].bounds方法。
  • 也不要使用外面写的一些工具类。
  • 注意NSUserDefault的使用,要使用[[NSUserDefaults alloc] initWithSuiteName:@"group.com.xx.oo.Share"]

创建extension

File -> New -> Target,选中share extension就可以创建一个新的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

编码

创建完毕以后可以看到有一个默认的ShareViewController,头文件继承了系统的SLComposeServiceViewController,我们自定义的就不需要它了,删不删随便。

屏幕快照 2018-07-10 14.32.29.png
在Share文件夹下新建一个控制器,继承UIViewcontroller就行,我这里叫CustomShareViewController。然后在这里的info.plist里,把新建的控制器加进去。把原先(上面)的键值换成新(下面)的。
分组.png
搭建UI

在Controller里,创建想要的UI。
我这里以获取Photo照片库的图片数据为例。
不要使用[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那个方法,会拿不到尺寸,然后界面显示不出来。
界面搭好了,就获取一下数据。

获取和展示数据

主要是通过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;
        }
    }];
}
取消和保存数据

界面显示弄好了,接下来就是cancelsave两个按钮的点击事件了。注意NSUserDefault的使用,要使用[[NSUserDefaults alloc] initWithSuiteName:@"group.com.xx.oo.Share"]
核心方法是[self.extensionContext cancelRequestWithError:][self.extensionContext completeRequestReturningItems: completionHandler:]
第二个方法里把你需要的数据放到沙盒里,这样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获取数据

AppDelegate- applicationDidBecomeActive:方法里拿到数据。

- (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"];
            //拿到数据了哈哈后
        }
        [[NSFileManager defaultManager]removeItemAtURL:fileURL error:NULL];
        //重置分享标识
        [userDefaults setBool:NO forKey:@"has-new-share"];
    }
}

结果是节个样几:


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

再见。

相关文章

网友评论

    本文标题:iOS Share Extension之自定义界面

    本文链接:https://www.haomeiwen.com/subject/ljbfpftx.html