ios

iOS shareSDK分享至第三方平台

2017-07-13  本文已影响61人  fulen

本文使用第三方mob进行分享,mob开放平台http://www.mob.com 下载所需的SDK,然后这里分享了微信,qq,新浪微博,豆瓣

1.1 将sdk导入项目中,具体细节参见mob官网,如图1.1

图1.1

1.2 添加白名单如图1.2

图1.2

1.2 添加各种依赖库如图1.3 (为避免日后更新升级,添加依赖库最好到mob官网查看)

图1.3

1.4 添加 url type 如图1.4(这里微信 qq 新浪需要)

图1.4

2 在appdelegte里面配置shareSDK的参数

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [[[JFShareFunction alloc] init] setShareSDK]; // 设置mob分享  此方法为新建类 在下面
    
    return YES;
}
#import <Foundation/Foundation.h>

// 分享
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

@interface JFShareFunction : NSObject

/**
 设置shareSDK
 */
- (void)setShareSDK;

/**
 share默认分享菜单

 @param imageArray 分享的图片
 @param urlString 分享的链接
 @param text 分享的内容
 @param title 分享的标题
 */
- (void)shareInfomationWithImageArray:(NSArray *)imageArray url:(NSString *)urlString text:(NSString *)text title:(NSString *)title;


/**
 自定义分享菜单

 @param imageArray 分享的图片
 @param urlString 分享的链接
 @param text 分享的内容
 @param title 分享的标题
 */
- (void)shareCustomInfomationWithImageArra:(NSArray *)imageArray url:(NSString *)urlString text:(NSString *)text title:(NSString *)title;


@end

2.1 先看一下mob默认的分享样式

#import "JFShareFunction.h"
#import <ShareSDKUI/SSUIEditorViewStyle.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
// 自定义分享菜单栏需要导入的头文件
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>
#import <ShareSDK/ShareSDK.h>
#import "JFShareCustom.h"
#import "WeiboSDK.h"


@class SSUIShareActionSheetItem;

@interface JFShareFunction ()

@property (strong , nonatomic) NSArray *PlatformTypeArray;

@end

@implementation JFShareFunction


- (NSArray *)PlatformTypeArray{
    _PlatformTypeArray = @[
                           @(SSDKPlatformTypeSinaWeibo),
                           @(SSDKPlatformTypeDouBan),
                           @(SSDKPlatformTypeMail),
                           @(SSDKPlatformTypeSMS),
                           @(SSDKPlatformSubTypeWechatSession),
                           @(SSDKPlatformSubTypeWechatTimeline),
                           @(SSDKPlatformTypeQQ),
                           ];
    return _PlatformTypeArray;
}

- (void)setShareSDK{
    
    [ShareSDK registerActivePlatforms:self.PlatformTypeArray
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO+Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:KVendor_Weibo_AppKey  // 微博
                                           appSecret:KVendor_Weibo_App_Secret
                                         redirectUri:KVendor_Weibo_redirectUri
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:    // 微信
                 [appInfo SSDKSetupWeChatByAppId:KVendor_WeChat_AppID  //wx272b73bc8474d024
                                       appSecret:KVendor_WeChat_App_Secret];
                 break;
             case SSDKPlatformTypeQQ:        // qq
                 [appInfo SSDKSetupQQByAppId:KVendor_QQ_AppID
                                      appKey:KVendor_QQ_App_key
                                    authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeDouBan:        // 豆瓣
                 [appInfo SSDKSetupDouBanByApiKey:KVendor_Douban_AppID
                                           secret:KVendor_Douban_App_key
                                      redirectUri:KVendor_Douban_redirectUri];
                 break;
             default:
                 break;
         }
     }];
    
}




// 分享
- (void)shareInfomationWithImageArray:(NSArray *)imageArray url:(NSString *)urlString text:(NSString *)text title:(NSString *)title {
    
    //poster
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    [shareParams SSDKSetupShareParamsByText:text
                                          images:imageArray
                                             url:[NSURL URLWithString:urlString]
                                           title:title
                                            type:SSDKContentTypeAuto];
    
    //有的平台要客户端分享需要加此方法,例如微博
    [shareParams SSDKEnableUseClientShare];
   SSUIShareActionSheetController *sheet = [ShareSDK showShareActionSheet:nil
                             items:self.PlatformTypeArray
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                           message:[NSString stringWithFormat:@"%@",error.userInfo[@"error_message"]]                                                                                      delegate:nil
                                                                 cancelButtonTitle:@"OK"
                                                                 otherButtonTitles:nil, nil];
                           NSLog(@"错误信息-----------%@",error.userInfo[@"error_message"]);
                           
                           [alert show];
                           break;
                       }
                       default:
                           break;
                   }
               }];
    // 跳过编辑页面直接分享  编辑页面如图2.4
   //  [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
 //    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeDouBan)];
    // [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeMail)];
  //   [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSMS)];
}
@end

2.2 点击分享按钮分享标题、图片、链接等

NSArray *imageArra = [NSArray arrayWithObjects:[UIImage imageNamed:@"poster"],nil];
            [[[JFShareFunction alloc] init] shareInfomationWithImageArray:imageArra url:@"http://test-m-stg.ppppoints.com/jfmall/index.htm" text:@"这是分享内容" title:@"这是分享title"];

2.3 点击分享按钮的试图如图2.3 ,这里mob的sdk判断了手机里面有没有安装需要分享的平台的客服端,如果没有,在分享菜单中就不显示,有就一排最多四个显示

图2.3

2.4 点击微博分享,会默认跳出编辑页面 ,如图2.4

图2.4

点击右上角share,跳转对应的web端或者客户端如图 2.4.1


图2.4.1

3 以上就集成好了share,如果想自定义分享菜单,如图3.1

图3.1

3.1 自建自定义分享页面类

#import <Foundation/Foundation.h>

@interface JFShareCustom : NSObject

+(void)shareWithContent:(id)publishContent;//自定义分享界面

@end
#import "JFShareCustom.h"
#import <QuartzCore/QuartzCore.h>
#import <ShareSDK/ShareSDK.h>

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

//腾讯开放平台(对应QQ和QQ空间)SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

#define SYSTEM_VERSION   [[UIDevice currentDevice].systemVersion floatValue]
#define KWidth_Scale    [UIScreen mainScreen].bounds.size.width/375.0f
// 颜色
#define UIColorFromRGB(rgbValue) [UIColor  colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0  green:((float)((rgbValue & 0xFF00) >> 8))/255.0  blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
// 适配
#define DevicesScale ([UIScreen mainScreen].bounds.size.height==480?1.00:[UIScreen mainScreen].bounds.size.height==568?1.00:[UIScreen mainScreen].bounds.size.height==667?1.17:1.29)


@implementation JFShareCustom

static id _publishContent;//类方法中的全局变量这样用(类型前面加static)
static UIVisualEffectView *_effectView;


+(void)shareWithContent:(id)publishContent/*只需要在分享按钮事件中 构建好分享内容publishContent传过来就好了*/
{
    _publishContent = publishContent;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    UIBlurEffect * blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    _effectView = [[UIVisualEffectView alloc]initWithEffect:blur];
    _effectView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [window addSubview:_effectView];
    _effectView.contentView.alpha = 0;
    _effectView.alpha = 0.3;
    
    /**
     点击退出手势
     */
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [_effectView addGestureRecognizer:tap];
    
    
    /**
     Share Content
     */
    UIView *shareView = [[UIView alloc] initWithFrame:CGRectMake(0, (SCREEN_HEIGHT-249 * DevicesScale), SCREEN_WIDTH, 249*DevicesScale)];
    shareView.tag = 441;
    shareView.backgroundColor = [UIColor colorWithRed:10 green:10 blue:10 alpha:1];
    [window addSubview:shareView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, shareView.frame.size.width, 45*KWidth_Scale)];
    titleLabel.text = @"分享到";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:18*KWidth_Scale];
    titleLabel.textColor = UIColorFromRGB(0x374552);
    titleLabel.backgroundColor = [UIColor clearColor];
    [shareView addSubview:titleLabel];
    
    NSArray *btnImages = @[@"sns_icon_24",@"sns_icon_22",@"sns_icon_6",@"sns_icon_23",@"sns_icon_1",@"sns_icon_18",@"sns_icon_19",@"sns_icon_5"];
    NSArray *btnTitles = @[ @"QQ", @"微信好友", @"QQ空间", @"朋友圈",@"微博",@"邮件",@"短信",@"豆瓣"];
    for (NSInteger i=0; i<btnImages.count; i++) {
        
        CGFloat bt_width =  85 * DevicesScale;
        if(SCREEN_HEIGHT == 568) {
            bt_width = 95 *DevicesScale;
        }
        CGFloat gap = (shareView.frame.size.width - 4*bt_width) / 5.0;
        CGFloat top = 0.0f;
        if (i<4) {
            top = 0*KWidth_Scale;
        }
        else{
            top = 0*KWidth_Scale + bt_width;
        }
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(gap * (i % 4 + 1) + i % 4 * bt_width, titleLabel.frame.origin.y + titleLabel.frame.size.height+top+i/4*(titleLabel.frame.origin.y+10), bt_width, bt_width)];
        [button setImage:[UIImage imageNamed:btnImages[i]] forState:UIControlStateNormal]; // @"home13"
        UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, bt_width - 10, bt_width, 20)];
        lbl.font = [UIFont systemFontOfSize:12*DevicesScale];
        lbl.textAlignment = NSTextAlignmentCenter;
        lbl.textColor = UIColorFromRGB(0x374552);
        lbl.text = btnTitles[i];
        [button addSubview:lbl];
        
        button.tag = 331+i;
        [button addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [shareView addSubview:button];
    }
    
    //为了弹窗不那么生硬,这里加了个简单的动画
    shareView.transform = CGAffineTransformMakeScale(1/300.0f, 1/270.0f);
    [UIView animateWithDuration:0.35f animations:^{
        shareView.transform = CGAffineTransformMakeScale(1, 1);
        _effectView.backgroundColor = [UIColor grayColor];
    } completion:^(BOOL finished) {
    }];
}

+(void)shareBtnClick:(UIButton *)btn
{
    
    int shareType = 0;
    id publishContent = _publishContent;
//    [MBProgressHUD showHUD];
    if (btn.tag == 339) {
        return;
    }
    switch (btn.tag) {
        case 331: {
            shareType = SSDKPlatformSubTypeQQFriend;
        }
            break;
        case 332: {
            shareType = SSDKPlatformSubTypeWechatSession;
        }
            break;
        case 333: {
            shareType = SSDKPlatformSubTypeQZone;
        }
            break;
        case 334: {
            shareType = SSDKPlatformSubTypeWechatTimeline;
        }
            break;
        case 335: {
            shareType = SSDKPlatformTypeSinaWeibo;
        }
            break;
        case 336: {
            shareType = SSDKPlatformTypeMail;
        }
            break;
        case 337: {
            shareType = SSDKPlatformTypeSMS;
        }
            break;
        case 338: {
            shareType = SSDKPlatformTypeDouBan;
        }
            break;
        default:
            break;
    }
    [self dismiss];
    
    
    
    // 默认有编辑页面
    [ShareSDK showShareEditor:shareType
           otherPlatformTypes:nil
                  shareParams:publishContent
          onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end){
              
//              [MBProgressHUD dismiss];
              switch (state) {
                  case SSDKResponseStateSuccess:
                  {
                      [UIAlertView showWithTitle:@"分享成功" message:@"" cancelButtonTitle:@"确定"];
                      break;
                  }
                  case SSDKResponseStateFail:
                  {
                      NSString *failMessage = [error.userInfo[@"error_message"] formatString];
                      if (failMessage.length == 0) {
                          failMessage = [error.userInfo[@"user_data"][@"msg"] formatString];
                      }
                      [UIAlertView showWithTitle:@"分享失败" message:failMessage cancelButtonTitle:@"OK"];
                      break;
                  }
                  default:
                      break;
              }
          }];
//
    // 跳过编辑页面
//    [ShareSDK share:shareType parameters:publishContent onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
//        [MBProgressHUD dismiss];
//        switch (state) {
//            case SSDKResponseStateSuccess:
//            {
//                [UIAlertView showWithTitle:@"分享成功" message:@"" cancelButtonTitle:@"确定"];
//                break;
//            }
//            case SSDKResponseStateFail:
//            {
//                NSString *failMessage = [error.userInfo[@"error_message"] formatString];
//                if (failMessage.length == 0) {
//                    failMessage = [error.userInfo[@"user_data"][@"msg"] formatString];
//                }
//                [UIAlertView showWithTitle:@"分享失败" message:failMessage cancelButtonTitle:@"OK"];
//                break;
//            }
//            default:
//                break;
//        }
//    }];
}

+ (void)dismiss {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *shareView = [window viewWithTag:441];
    //为了弹窗不那么生硬,这里加了个简单的动画
    shareView.transform = CGAffineTransformMakeScale(1, 1);
    [UIView animateWithDuration:0.35f animations:^{
        shareView.transform = CGAffineTransformMakeScale(1/300.0f, 1/270.0f);
        _effectView.contentView.alpha = 0;
    } completion:^(BOOL finished) {
        [shareView removeFromSuperview];
        [_effectView removeFromSuperview];
    }];
}




@end

以下有几个需要注意的地方,使用默认的actionSheet弹出分享试图的时候,可以设置跳过编辑页面

 SSUIShareActionSheetController *sheet = [ShareSDK showShareActionSheet:nil
                             items:self.PlatformTypeArray
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
// 这里可以判断点击的是哪个平台
           if (platformType == SSDKPlatformTypeDouBan) {

                 // 做一些事情
                   }
                  
    // 跳过编辑页面直接分享  (打开注释即可)
//    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
//    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeDouBan)];
//    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeMail)];
//    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSMS)];
}

有几个需要注意的地方:

1 邮件分享 :如果没有设置好邮件的账号密码,默认是会分享并且回调回来显示分享成功,但是实际上可能邮件并没有发送成功,mob客服说现在没法监听邮件是否发送成功

2 豆瓣分享 :不管手机有没有下载豆瓣app,都默认网页版分享豆瓣,没法掉起豆瓣的app

3 新的自定义页面如图 3.1

图3.1

#import <Foundation/Foundation.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "JFShareInformation.h"


@interface JFShareFunction : NSObject

/**
 设置shareSDK
 */
- (void)setShareSDK;

/**
 自定义分享菜单

 @param information 分享的信息
 */
- (void)shareCustomInfomationWithmodel:(JFShareInformation *)information;


@end

#import "JFShareFunction.h"
#import <ShareSDK/ShareSDK.h>
#import "JFShareCustom.h"


@class SSUIShareActionSheetItem;

@interface JFShareFunction ()

@property (strong , nonatomic) NSArray *PlatformTypeArray;

@end

@implementation JFShareFunction


- (NSArray *)PlatformTypeArray{
    _PlatformTypeArray = @[
                           @(SSDKPlatformTypeSinaWeibo),
                           @(SSDKPlatformTypeDouBan),
                           @(SSDKPlatformTypeMail),
                           @(SSDKPlatformTypeSMS),
                           @(SSDKPlatformSubTypeWechatSession),
                           @(SSDKPlatformSubTypeWechatTimeline),
                           @(SSDKPlatformTypeQQ),
                           ];
    return _PlatformTypeArray;
}

- (void)setShareSDK{
    
    [ShareSDK registerActivePlatforms:self.PlatformTypeArray
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO+Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:KVendor_Weibo_AppKey  // 微博
                                           appSecret:KVendor_Weibo_App_Secret
                                         redirectUri:KVendor_Weibo_redirectUri
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:    // 微信
                 [appInfo SSDKSetupWeChatByAppId:KVendor_WeChat_AppID  //wx272b73bc8474d024
                                       appSecret:KVendor_WeChat_App_Secret];
                 break;
             case SSDKPlatformTypeQQ:        // qq
                 [appInfo SSDKSetupQQByAppId:KVendor_QQ_AppID
                                      appKey:KVendor_QQ_App_key
                                    authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeDouBan:        // 豆瓣
                 [appInfo SSDKSetupDouBanByApiKey:KVendor_Douban_AppID
                                           secret:KVendor_Douban_App_key
                                      redirectUri:KVendor_Douban_redirectUri];
                 break;
             default:
                 break;
         }
     }];
}



- (void)shareCustomInfomationWithmodel:(JFShareInformation *)information {
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:information.content
                                     images:information.imageurl
                                        url:[NSURL URLWithString:information.shareurl]
                                      title:information.title
                                       type:SSDKContentTypeAuto];
    
    NSString *content = [NSString stringWithFormat:@"%@%@",information.content,information.shareurl];
    // 定制新浪微博的分享内容   新浪微博的url要放在content后面,不能放在url里面
    [shareParams SSDKSetupSinaWeiboShareParamsByText:content
                                               title:information.title
                                               image:information.imageurl
                                                 url:nil
                                            latitude:0
                                           longitude:0
                                            objectID:nil
                                                type:SSDKContentTypeAuto];
    //调用自定义分享
    [JFShareCustom shareWithContent:shareParams];
}



@end
#import <UIKit/UIKit.h>

/**
 分享菜单自定义button
 */
@interface JFShareButton : UIButton

@end
#import "JFShareButton.h"

@implementation JFShareButton

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.titleLabel.textColor = [UIColor darkGrayColor];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat w = self.frame.size.width;
    CGFloat h = self.frame.size.height;
    self.titleLabel.frame = CGRectMake(0, h - 33/2*kDeviceWidthScaleToiPhone6, w, 33/2*kDeviceWidthScaleToiPhone6);
    if (self.tag == 332) {
        self.titleLabel.frame = CGRectMake(-10*kDeviceWidthScaleToiPhone6, h - 33/2*kDeviceWidthScaleToiPhone6, w+20*kDeviceWidthScaleToiPhone6, 33/2*kDeviceWidthScaleToiPhone6);
    }
    self.imageView.frame = CGRectMake((w - 50*kDeviceWidthScaleToiPhone6)/2, 0, 50*kDeviceWidthScaleToiPhone6, 50*kDeviceWidthScaleToiPhone6);
}

@end
上一篇下一篇

猜你喜欢

热点阅读