iOS自定義UIActivity實現分享詳解

我們在使用系統分享的時候,會發現有些平臺系統分享是不支持的,比如你想分享到四個平臺,系統支持三個,另一個不支持。這個時候我們可以通過自定義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>
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章