iOS自定义UIActivity实现分享详解

我们在使用系统分享的时候,会发现有些平台系统分享是不支持的,比如你想分享到四个平台,系统支持三个,另一个不支持。这个时候我们可以通过自定义UIActivity将另一个平台加到系统分享中。

UIActivity是个抽象类,我们需要继承他,实现他定义的方法。我们以分到Instagram为例,详细的说明具体实现过程。先来看一下效果,这里有两个Instagram,一个是系统的,一个是我自定义的(我这个图片是随便找的),点击之后都能成功分享到Instagram。
iOS自定义UIActivity实现分享详解_第1张图片
直接上代码,每一处我都写了注释:

.h文件

// 设定一个类型
UIKIT_EXTERN UIActivityType const UIActivityTypeShareToInstagram;

NS_ASSUME_NONNULL_BEGIN
@interface InstagramActivity : UIActivity

@end
NS_ASSUME_NONNULL_END

.m文件

#import "InstagramActivity.h"

UIActivityType const UIActivityTypeShareToInstagram = @"com.report.activity.ShareToInstagarm"; // 格式抄的苹果的

@interface InstagramActivity ()
@property (nonatomic, strong) NSString *dataURL; // 分享数据URL
@end

@implementation InstagramActivity

// 用来判断是什么Activity类型
- (NSString *)activityType{
    return UIActivityTypeShareToInstagram;
}

// 决定在UIActivityViewController中显示的位置,最上面是AirDrop,中间是Share,下面是Action
+ (UIActivityCategory)activityCategory{
    return UIActivityCategoryShare;
}

// 显示的Title
- (NSString *)activityTitle{
    return @"Instagram";
}

// 显示的图标
- (UIImage *)activityImage{
    /*
    For iPhone and iPod touch, images on iOS 7 should be 60 by 60 points; on earlier versions of iOS, you should use images no larger than 43 by 43 points. For iPad, images on iOS 7 should be 76 by 76 points; on earlier versions of iOS you should use images no larger than 60 by 60 points. On a device with Retina display, the number of pixels is doubled in each direction.
     */
    if ([[UIDevice currentDevice].model isEqualToString:@"iPad"]) {
    	 return [UIImage imageNamed:@"instagram_76x76"];
    }else{
    	return [UIImage imageNamed:@"instagram_60x60"];
    }
}

#pragma mark   -  数据处理
// 根据item的不同类型判断是否显示
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems{

    // 我们要实现的instagram分享,只支持图片  (如果是微信,还要判断是否安装微信)
    BOOL support = NO;
    for (id obj in activityItems) {
        if ([obj isKindOfClass:UIImage.class]) {
            support = YES;
        }
        // 有一个支持就取消遍历
        if (support) break;
    }
    return support;
}


- (void)prepareWithActivityItems:(NSArray *)activityItems{

    // 点击动作即将执行的准备阶段, 可以用来处理一下值或者逻辑, items就是要传输的数据
    for (id obj in activityItems) {

        if([obj isKindOfClass:UIImage.class]){
        	// 获取图片的URL
            [self getImageURLWithImage:obj complete:^(NSString *text) {
                 self.dataURL = text;
            }];

            break; // 只支持分享一张, 这里直接跳出循环
        }
    }
}


#pragma mark   -  事件处理
// 点击UIActivity的动作消息,处理点击后的相应逻辑, 没有自定义的UIViewController才会调用此方法, 需要在最后消除掉UIActivityviewController
- (void)performActivity{
    NSString *instagramURL = nil;

    instagramURL = [NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=",self.dataURL.length ? self.dataURL:@"assets-library"];

    if ([[UIApplication sharedApplication] canOpenURL:instagramURL.url]) {
        [[UIApplication sharedApplication] openURL:instagramURL.url];
    }
    else{
        AlertView *alert = [[AlertView alloc] initWithContent:@"You didn't install \"Instagram\",Please try again after install \"Instagram\""];
        alert.singleButton = YES;
        [alert show];
    }
    [self activityDidFinish:YES];
}


// 获取图片的URL 与本文关系不大,可以忽略
- (void)getImageURLWithImage:(UIImage *)image complete:(StringBlock)complete{

    if (!image) return;

    // 先保存到相册
    [LGImageManager saveImage:image completion:^(NSError *error) {

        // 其实分享的URL直接用 instagram://library?AssetPath=assets-library ins会自动帮我们获取相册最后一张图片,我们只需要保存一下就OK了

        if (TARGET_IPHONE_SIMULATOR == 1 && TARGET_OS_IPHONE == 1) {return;}

        // 从相册获取最后一张图片资源
        PHAsset *asset = [LGImageManager getAllAssetInPhotoAlbumWithAscending:NO allowSelectVideo:NO allowSelectImage:YES allowSelectGif:NO allowSelectLivePhoto:NO limitCount:1].firstObject;

        NSString *imageURL = [NSString stringWithFormat:@"file:///var/mobile/Media/%@/%@",[asset valueForKey:@"directory"],[asset valueForKey:@"filename"]];
        if (complete && imageURL) complete(imageURL);
    }];
}

@end

















已经自定义了InstagramActivity,下面说说使用

- (void)shareToInstagram{
	
	// 分享的内容: 一张图片
    NSArray *activityItems = @[[UIImage imageNamed:@"share_content"]];
    // 创建一个InstagramActivity对象 放在数组里,也可以添加其他的类型
    NSArray *activities = @[[InstagramActivity new]];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:activities];
    // 执行performActivity方法之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
		// do something
    };
    if ([[UIDevice currentDevice].model isEqualToString:@"iPad"]) {
        activityVC.modalInPopover = true;

        activityVC.popoverPresentationController.sourceView = self.view;
        activityVC.popoverPresentationController.sourceRect = CGRectMake([UIScreen mainScreen].bounds.size.width * 0.5,self.view.bounds.size.height, 1.0, 1.0);
    }
    [self presentViewController:activityVC animated:YES completion:nil];
}






要成功调起Instagram,需要在info.plist文件中添加白名单。右击info.plist->Opne as->Source Code,然后加上下面代码

    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>instagram</string>
    </array>
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>We need to access your album to save picture</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>We need to access your album to get pictures</string>
    

你可能感兴趣的:(学习笔记)