将App添加到系统分享列表(相册和截屏)

时间:2024-04-06 15:14:40

系统相册点击分享 拉起客户端 获取图片发送或上传

将App添加到系统分享列表(相册和截屏)

2.1 创建Share Extension扩展Target

1、file—>new——>target
将App添加到系统分享列表(相册和截屏)

2、iOS—> Application Extension—>Share Extension,点击Next

将App添加到系统分享列表(相册和截屏)

3、给扩展起个名字,点击“Finish”

将App添加到系统分享列表(相册和截屏)

4.这时候会提示创建一个Scheme,点击“Activate”
将App添加到系统分享列表(相册和截屏)

创建Share Extension完成。编译运行。XCode中会弹出界面让我们选择一个iOS的App来运行Extension(真机有图片)。如图:

将App添加到系统分享列表(相册和截屏)

然后点击“Run”来进行调试运行启动系统照片,如图: 

将App添加到系统分享列表(相册和截屏)


如果不想使用模板提供的storyboard文件,打开share的info.plist  移除NSExtensionMainStoryboard 键值对,并添加NSExtensionPrincipalClass键值对,使用自己创建的Controller的名字作为值

NSExtensionActivationSupportsImageWithMaxCount(数字6是规定最多可以选择6张图片)

将App添加到系统分享列表(相册和截屏)




myShareViewController 中的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imagesArr = [NSMutableArray array];
    self.ImagesStr = nil;
    self.view.backgroundColor = [UIColor colorWithRed:0.00 green:0.00 blue:0.00 alpha:0.50];
    self.bacView = [[UIView alloc] initWithFrame:CGRectMake(30, [UIScreen mainScreen].bounds.size.height/2-200, [UIScreen mainScreen].bounds.size.width-60, 400)];
    self.bacView.layer.cornerRadius = 5;
    self.bacView.layer.masksToBounds = YES;
    self.bacView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bacView];
    ///
    self.nanView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width-60, 0.5)];
    self.nanView.backgroundColor = [UIColor lightGrayColor];
    [self.bacView addSubview:self.nanView];
    ///
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    self.cancelButton.tintColor = [UIColor orangeColor];
    self.cancelButton.frame = CGRectMake(10, 22, 50, 20);
    [self.bacView addSubview:self.cancelButton];
    [self.cancelButton addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
    ///
    self.postButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.postButton setTitle:@"发送" forState:UIControlStateNormal];
    self.postButton.tintColor = [UIColor orangeColor];
    self.postButton.frame = CGRectMake(self.bacView.frame.size.width-60, 22, 50, 20);
    [self.bacView addSubview:self.postButton];
    [self.postButton addTarget:self action:@selector(postButtonAction) forControlEvents:UIControlEventTouchUpInside];
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作 获取选中的图片的image
        for (NSExtensionItem *item in self.extensionContext.inputItems) {
            NSInteger count = item.attachments.count;
            for (NSItemProvider *itemProvider in item.attachments) {
                if ([itemProvider hasItemConformingToTypeIdentifier:@"public.image"]) {
                    [itemProvider loadItemForTypeIdentifier:@"public.image" options:nil completionHandler:^(UIImage *image, NSError *error) {
                        [self.imagesArr addObject:image];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if (self.imagesArr.count == count) {
                                [self createScrollView];
                            }
                        });
                    }];
                }
            }
        }
    });
}
/// 数组转成”,"间隔的字符串方便存取
-(NSString *)stringTOjson:(NSMutableArray *)temps{
    return [temps componentsJoinedByString:@","];
}
- (void)createScrollView{
    self.bigImageScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.bacView.frame.size.width, 400-64)];
    self.bigImageScroll.pagingEnabled = YES;
    [self.bacView addSubview:self.bigImageScroll];
    self.bigImageScroll.backgroundColor = [UIColor whiteColor];
    self.bigImageScroll.contentSize = CGSizeMake(self.imagesArr.count*self.bacView.frame.size.width, 0);
   for (NSInteger i = 0; i<self.imagesArr.count; i++) {
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(i*self.bacView.frame.size.width, 0, self.bacView.frame.size.width, 400-64)];
        [image setContentScaleFactor:[[UIScreen mainScreen] scale]];
        image.contentModeUIViewContentModeScaleAspectFit;
        image.clipsToBounds  = YES;
        [self.bigImageScroll addSubview:image];
        image.backgroundColor = [UIColor whiteColor];
        image.image = self.imagesArr[i];
    }
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.Micteach.Parents.ImageShare"];
    ////imageKeyArr 存储图片data的key数组
    NSMutableArray *imageKeyArr = [NSMutableArray array];
        for (UIImage *image in self.imagesArr) {
            //UIImage转换为NSData
            NSData *imageData = UIImagePNGRepresentation(image);
            NSString *key = [self ret32bitString];
            [userDefaults setObject:imageData forKey:key];
            [imageKeyArr addObject:key];
        }
    [userDefaults setObject:[self stringTOjson:imageKeyArr] forKey:@"shareImageArr"];
    //用于标记是新的分享
    [userDefaults setBool:YES forKey:@"newshare"];
}
/// 32位随机字符串
- (NSString *)ret32bitString{
    char data[32];
    for (int x=0;x<32;data[x++] = (char)('A' + (arc4random_uniform(26))));
    return [[NSString alloc] initWithBytes:data length:32 encoding:NSUTF8StringEncoding];
}
- (void)cancelButtonAction{
    [self.extensionContext cancelRequestWithError:[NSError errorWithDomain:@"CustomShareError" code:NSUserCancelledError userInfo:nil]];
}
- (void)postButtonAction{
    //执行分享内容处理  拉起寄主App(customURL是怎么来的?调研openUrl)
    NSString *customURL = @"cloudschool://";
    UIResponder* responder = self;
    while ((responder = [responder nextResponder]) != nil){
        if([responder respondsToSelector:@selector(openURL:)] == YES){
            [responder performSelector:@selector(openURL:) withObject:[NSURL URLWithString:customURL]];
            [self.extensionContext completeRequestReturningItems:nil completionHandler:NULL];
        }
    }
}
到这里 可以拉起宿主App
下面是如何在宿主App中获取图片的存储数组

使用App Groups服务,使自己的应用之间通过NSUserDefaults进行相互的数据传输

到开发者中心为创建的ImageShare工程添加App ID ,,打开ImageShare工程和宿主工程的App services的App groups 功能(由于我的工程使用的automatically manage signing 所以未到开发者中心创建App ID,直接在工程开启App Groups后自动生成的,对于不是automatically manage signing具体的过程自己研究一下吧

然后分别打开容器应用和分享应用的项目配置的Capabilities页签,**App Groups特性,添加App groups  格式是:“group.+bundle identifier”如图:

将App添加到系统分享列表(相册和截屏)

将App添加到系统分享列表(相册和截屏)

在宿主App的Appdelegate中获取分享数据
- (void)applicationDidBecomeActive:(UIApplication *)application {
    //获取共享的UserDefaults  注意黄色字体与ImageShare的App groups匹配
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.Micteach.Parents.ImageShare"];
    if ([userDefaults boolForKey:@"newshare"]){
        NSArray  *array = [[userDefaults objectForKey:@"shareImageArr"] componentsSeparatedByString:@",”];

 NSMutableArray *imagesDataArr = [NSMutableArray array];
   /// 取出图片data
    for (NSString *key in array) {
        NSData *data = [userDefaults objectForKey:key];
        [imagesDataArr addObject:data];
    }
        //重置分享标识
        [userDefaults setBool:NO forKey:@"newshare"];
    }
}
imagesDataArr便是获取到的图片的数组,,具体接下来是将图片进行发送还是上传服务器等操作,,按照自己的逻辑来操作。。。。。。。。。。。。。。。。