我們在使用系統分享的時候,會發現有些平台系統分享是不支援的,比如你想分享到四個平台,系統支援三個,另一個不支援。這個時候我們可以通過自定義
UIActivity
将另一個平台加到系統分享中。
UIActivity
是個抽象類,我們需要繼承他,實作他定義的方法。我們以分到Instagram為例,詳細的說明具體實作過程。先來看一下效果,這裡有兩個Instagram,一個是系統的,一個是我自定義的(我這個圖檔是随便找的),點選之後都能成功分享到Instagram。

直接上代碼,每一處我都寫了注釋:
.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>