iOS端游戏SDK 分享聚合

SDK 分享聚合单例

分享包括微信好友分享、微信朋友圈分享、qq好友分享、微博分享。
单例包括弹框block,回调函数,分享功能。
回调因为要告诉游戏lua代码,所以我用的是通知,方便回调。
首先是分享界面,AoJiaoShareView,因为调用是游戏界面调用,lua调用c++,c++调用OC,所以单例创建界面,界面也是源生OC写的。
首先根据微信开放平台,qq开放平台,微博开放平台增加依赖库。

AoJiaoShareView.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface AoJiaoShareView : UIView
-(instancetype)initWithFrame:(CGRect)frame withVC:(UIViewController *)vc;
- (void)showWithCompleteBlock:(void (^)(NSInteger))block;
- (void)hide;

@end

NS_ASSUME_NONNULL_END

AoJiaoShareView.m

#define UISCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define UISCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define kMaxX(X) CGRectGetMaxX(X)
#define kMaxY(Y) CGRectGetMaxY(Y)


#import "AoJiaoShareView.h"
@interface AoJiaoShareView ()<UIGestureRecognizerDelegate>

@property (strong, nonatomic) UIView *bgView;
@property (strong, nonatomic) UIButton *cancelBtn;
@property (strong, nonatomic) UITapGestureRecognizer *tap;

@property (nonatomic, copy) void (^block)(NSInteger);

@property (nonatomic, copy) NSArray *resources;
@end
@implementation AoJiaoShareView

-(instancetype)initWithFrame:(CGRect)frame withVC:(UIViewController *)vc{
    self = [super initWithFrame:frame];
    if (self) {
        [self createViewWithVC:vc];
    }
    return self;
}

#pragma mark -懒加载
-(NSArray *)resources{
    if (_resources == nil) {
        _resources =@[
        @[@"微博", @"share_icon0"],
        @[@"微信", @"share_icon1"],
        @[@"QQ", @"share_icon2"],
        @[@"朋友圈", @"share_icon3"],
        ];
    }
    return _resources;
}

-(UIView *)bgView{
    if (_bgView == nil) {
        _bgView = [UIView new];
    }
    return _bgView;
}

-(UIButton *)cancelBtn{
    if (_cancelBtn == nil) {
        _cancelBtn = [[UIButton alloc] init];
        _cancelBtn.backgroundColor = [UIColor blueColor];
        [_cancelBtn setTitle:@"取消" forState:0];
        [_cancelBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
        [_cancelBtn setTitleColor:UIColor.whiteColor forState:0];
    }
    return _cancelBtn;
}

-(UITapGestureRecognizer*)tap{
    if (_tap == nil) {
        _tap = [[UITapGestureRecognizer alloc] init];
        [_tap addTarget:self action:@selector(onTap:)];
        _tap.numberOfTapsRequired = 1;
        _tap.delegate = self;
    }
    return _tap;
}
#pragma mark -UIInit
-(void)createViewWithVC:(UIViewController *)vc{
    
    
    self.bgView.frame = CGRectMake(0, 0, UISCREEN_WIDTH,UISCREEN_HEIGHT);
    _bgView.backgroundColor = [UIColor clearColor];
    [self addSubview:_bgView];
    
    [_bgView addGestureRecognizer:self.tap];
    
    UIImageView *bgImg = [UIImageView new];
    bgImg.frame = CGRectMake(0, vc.view.bounds.size.height-50-100, vc.view.bounds.size.width, 100);
    bgImg.backgroundColor = [UIColor greenColor];
    bgImg.userInteractionEnabled = YES;
    [_bgView addSubview:bgImg];
    
    //循环创建分享按钮
    for (int i = 0; i<self.resources.count; i++) {
        float jiange = (UISCREEN_WIDTH - self.resources.count*50)/5;
        UIImageView *btnimg = [UIImageView new];
        btnimg.frame = CGRectMake(i*50 + jiange * (i+1), 10, 50, 60);
        btnimg.backgroundColor = UIColor.blueColor;
        btnimg.image = [UIImage imageNamed:self.resources[i][1]];
        [bgImg addSubview:btnimg];
        
        UILabel *titleLab = [UILabel new];
        titleLab.frame = CGRectMake(i*50 + jiange  * (i+1), kMaxY(btnimg.frame) + 5, 50, 20);
        titleLab.text = self.resources[i][0];
        titleLab.font = [UIFont systemFontOfSize:15];
        titleLab.textAlignment = 1;
        titleLab.textColor = [UIColor blackColor];
        [bgImg addSubview:titleLab];
        
        UIButton *btn = [UIButton new];
        btn.frame = CGRectMake(i*50 +  jiange  * (i+1), 0, 50, 100);
        btn.tag = i;
        [btn addTarget:self action:@selector(onPressedShareBtn:) forControlEvents:UIControlEventTouchUpInside];
        [bgImg addSubview:btn];
        
        
    }
    
    self.cancelBtn.frame = CGRectMake(0, kMaxY(bgImg.frame), UISCREEN_WIDTH, 50);
    [_bgView addSubview:_cancelBtn];
    
}

- (void)showWithCompleteBlock:(void (^)(NSInteger))block;
{
    self.block = block;
    [UIView animateWithDuration:0 animations:^{
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.3f];
    }];
}

- (void)hide {
    [UIView animateWithDuration:0 animations:^{
        self.backgroundColor = [UIColor clearColor];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)onTap:(id)sender {
    [self hide];
}

- (void)onPressedShareBtn:(UIButton *)sender {
    if (self.block) {
        self.block(sender.tag);
    }
    [self hide];
}

#pragma mark - UIGestureRecognizerDelegate
 
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    if ([touch.view isEqual:self.bgView])
    {
        return YES;
    }
    else
    {
        return NO;
    }

}
@end

逻辑控制单例,回调是通知。
AoJiaoShareManager.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

#define AOJIAO_SHARE_FINISH_SUCCESS_KEY @"AOJIAO_SHARE_FINISH_SUCCESS_KEY"
#define AOJIAO_SHARE_FINISH_FAIL_KEY @"AOJIAO_SHARE_FINISH_FAIL_KEY"

@interface AoJiaoShareManager : NSObject


+ (AoJiaoShareManager * __nonnull)sharedInstance;

+ (BOOL)handleOpenUrl:(nullable NSURL *)url sourceApplication:(nullable NSString *)sourceApplication;

- (void)showWithTitle:(NSString * __nullable)aTitle image:(NSString * __nullable)aImage intro:(NSString * __nullable)aIntro url:(NSString * __nullable)aUrl dataDic:(NSDictionary * __nullable)adataDic;


@end

NS_ASSUME_NONNULL_END

AoJiaoShareManager.m

//微博id
#define WeiboAppKey         @"" //新浪微博Appkey
#define WeiboRedirectURI    @"" //新浪微博回调地址
//微信id
#define WeixinAppKey        @"" //微信Appkey
#define WeixinAppSecret     @"" //微信appAppSecret
#define WeixinMINIID        @"" //微信小程序id
#define WeixinUniversalLink @"" //微信开发者Universal Link
//腾讯id
#define QQAppKey            @"" //QQ分享Appkey
#define QQUniversalLink     @"" //QQUniversalLink

#define WEAK_SELF __weak __typeof(self)weakSelf = self

#define STRONG_SELF STRONG_SELF_NIL_RETURN

#define STRONG_SELF_NIL_RETURN __strong __typeof(weakSelf)self = weakSelf; if ( ! self) return ;

#undef    DEF_SINGLETON
#define DEF_SINGLETON( __class ) \
+ (__class * __nonnull)sharedInstance \
{ \
static dispatch_once_t once; \
static __class * __singleton__; \
dispatch_once(&once, ^{ __singleton__ = [[__class alloc] init]; } ); \
return __singleton__; \
}

#import "AoJiaoShareManager.h"
#import "AoJiaoShareView.h"

#import <FYWeixin/WXApi.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WeiboSDK.h"

@interface AoJiaoShareManager ()
<
WXApiDelegate,
WeiboSDKDelegate,
QQApiInterfaceDelegate,
TencentSessionDelegate
>

@property (nonatomic, strong) TencentOAuth *tencentOAuth;

@property (nonatomic, copy) NSDictionary *wbShareInfo;

@property (nonatomic, copy) NSString *wbToken;

@property (nonatomic, strong) NSMutableArray *permissionArray;

@property (assign) BOOL share;

@end
@implementation AoJiaoShareManager

DEF_SINGLETON(AoJiaoShareManager);

#pragma mark - 单例init
- (instancetype)init
{
    self = [super init];
    
    [WeiboSDK registerApp:WeiboAppKey];
    [WXApi registerApp:WeixinAppKey universalLink:WeixinUniversalLink];
    self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQAppKey andUniversalLink:QQUniversalLink andDelegate:self];
    
    return self;
}

- (void)dealloc {
    NSLog(@"[%@ call %@]", [self class], NSStringFromSelector(_cmd));
}

#pragma mark - 分享
+ (BOOL)handleOpenUrl:(nullable NSURL *)url sourceApplication:(nullable NSString *)sourceApplication
{
    NSString *urlstr = [NSString stringWithFormat:@"%@",url];
    if ([urlstr containsString:WeixinAppKey]) {
        return [WXApi handleOpenURL:url delegate:[AoJiaoShareManager sharedInstance]];
    }
    else if ([sourceApplication isEqualToString:@"com.tencent.mqq"] ||[sourceApplication isEqualToString:@"com.tencent.mipadqq"]) {
        [QQApiInterface handleOpenURL:url delegate:[AoJiaoShareManager sharedInstance]];
        return [TencentOAuth HandleOpenURL:url];
    }
    else if ([sourceApplication isEqualToString:@"com.sina.weibo"] ||[sourceApplication isEqualToString:@"com.sina.weibohd"]) {
        return [WeiboSDK handleOpenURL:url delegate:[AoJiaoShareManager sharedInstance]];
    }
    
    return NO;
}

- (void)showWithTitle:(NSString * __nullable)aTitle image:(NSString * __nullable)aImage intro:(NSString * __nullable)aIntro url:(NSString * __nullable)aUrl dataDic:(NSDictionary * __nullable)adataDic
{
    self.share = true;
    
    UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
    UIViewController *rootViewController = window.rootViewController;
    AoJiaoShareView *shareView = [[AoJiaoShareView alloc] initWithFrame:CGRectMake(0, 0, rootViewController.view.bounds.size.width, rootViewController.view.bounds.size.height) withVC:rootViewController];
    [rootViewController.view addSubview:shareView];
    
    WEAK_SELF;
    [shareView showWithCompleteBlock:^(NSInteger selectedIndex) {
        STRONG_SELF;
        [self showWithTitle:aTitle image:aImage intro:aIntro url:aUrl selectedIndex:selectedIndex dataDic:adataDic];
    }];
}

- (void)showWithTitle:(NSString * __nullable)aTitle image:(NSString * __nullable)aImage intro:(NSString * __nullable)aIntro url:(NSString * __nullable)aUrl selectedIndex:(NSInteger)selectedIndex dataDic:(NSDictionary * __nullable)adataDic
{
    
    NSString *title = aTitle.copy;
    NSString *intro = aIntro.copy;
    NSURL *imageUrl = [NSURL URLWithString:aImage.copy];
    
    NSString *url = [aUrl.copy stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *text = [NSString stringWithFormat:@"《%@》#魂器学院#", title];
    
    if (selectedIndex == 0) {
           //微博分享
            NSMutableDictionary *params = @{}.mutableCopy;
            params[@"title"] = aTitle;
            params[@"intro"] = aIntro;
            params[@"image"] = aImage;
            params[@"url"] = aUrl;
            self.wbShareInfo = params;
            
            WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
            authRequest.redirectURI = WeiboRedirectURI;
            authRequest.scope = @"all";
            [WeiboSDK sendRequest:authRequest];  
    }
    else if (selectedIndex == 1 || selectedIndex == 3) {
        if (![WXApi isWXAppInstalled]) {
            NSLog(@"无法使用微信分享");
            return ;
        }
        
        if (![WXApi isWXAppSupportApi]) {
            NSLog(@"无法使用微信分享");
            return ;
        }
        if (adataDic == nil) {
            //没有小程序分享功能
            WXImageObject *imageObject = [WXImageObject object];
            imageObject.imageData = [NSData dataWithContentsOfURL:imageUrl];

            WXMediaMessage *message = [WXMediaMessage message];
            message.thumbData = [NSData dataWithContentsOfURL:imageUrl];
            message.mediaObject = imageObject;

            SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            if (selectedIndex == 1) {
                req.scene = WXSceneSession;
            }
            else {
                req.scene = WXSceneTimeline;

            }
            [WXApi sendReq:req completion:nil];
            
        }
        else{
            //有小程序分享功能
            WXMiniProgramObject *object = [WXMiniProgramObject object];
            object.webpageUrl = url;
            object.userName = WeixinMINIID;
            object.path = [NSString stringWithFormat:@"pages/%@?id=%@",adataDic[@"type"],adataDic[@"workId"]];
            object.hdImageData = [NSData dataWithContentsOfURL:imageUrl];
            object.withShareTicket = NO;
            object.miniProgramType = WXMiniProgramTypeRelease;
            
            WXMediaMessage *message = [WXMediaMessage message];
            message.title = title;
            message.description = intro;
            message.thumbData = nil;  //兼容旧版本节点的图片,小于32KB,新版本优先
            //使用WXMiniProgramObject的hdImageData属性
            message.mediaObject = object;

            SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
            req.bText = NO;
            req.message = message;
            req.scene = WXSceneSession;  //目前只支持会话
            [WXApi sendReq:req completion:^(BOOL success) {
                NSLog(@"微信分享成功");
            }];
            if (selectedIndex == 1) {
                req.scene = WXSceneSession;
            }
            else {
                //            req.scene = WXSceneTimeline;
                NSLog(@"小程序暂时不能分享至朋友圈");
            }
            
           [WXApi sendReq:req completion:^(BOOL success) {
                NSLog(@"微信分享成功");
            }];
        }
        
        
    }
    else if (selectedIndex == 2) {
        if (![QQApiInterface isQQInstalled]) {
            NSLog(@"无法使用QQ分享");
            return;
        }
        
        if (![QQApiInterface isQQSupportApi]) {
            NSLog(@"无法使用QQ分享");
            return;
        }
        
        QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url]
                                                            title:title
                                                      description:intro
                                                  previewImageURL:imageUrl];
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
        [QQApiInterface sendReq:req];
    }
}

//分享成功任务完成
-(void)shareTaskFinishd{
    NSLog(@"分享任务完成");
    NSDictionary *dict = @{@"status":@(1)};
    [[NSNotificationCenter defaultCenter]postNotificationName:AOJIAO_SHARE_FINISH_SUCCESS_KEY object:dict];
    
}

#pragma mark -weibo Delegate
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    NSLog(@"didReceiveWeiboRequest");
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    NSLog(@"didReceiveWeiboResponse");
    if ([response isKindOfClass:[WBSendMessageToWeiboResponse class]]) {
        WBSendMessageToWeiboResponse *res = (id)response;
        if (res.statusCode == WeiboSDKResponseStatusCodeSuccess) {
            NSLog(@"分享成功");
            [self shareTaskFinishd];
        }
        else if (res.statusCode == WeiboSDKResponseStatusCodeUserCancel) {
            NSLog(@"分享取消了");
        }
        else {
            NSLog(@"分享失败");
        }
    }
}
#pragma mark - QQ || weixin delegate
-(void)onReq:(id)req
{
    NSLog(@"onReq");
}

- (void)onResp:(id)resp
{
    NSLog(@"onResp");
    if ([resp isKindOfClass:[SendMessageToQQResp class]]) {
        SendMessageToQQResp *qq = resp;
        if (!self.share) {
            return;
        }
        if ([qq.result isEqualToString:@"0"]) {
            NSLog(@"分享成功");
            [self shareTaskFinishd];
        }
        else if ([qq.result isEqualToString:@"-4"]) {
            NSLog(@"分享取消了");
        }
        else {
            NSLog(@"分享失败");
        }
    }
    else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        BaseResp *weixin = resp;
        if (weixin.errCode == WXSuccess) {
            NSLog(@"分享成功");
            [self shareTaskFinishd];
        }
        else if (weixin.errCode == WXErrCodeUserCancel) {
            NSLog(@"分享取消了");
        }
        else {
            NSLog(@"分享失败");
        }
    }
}
@end

需要在AppDelegate.m里增加分享回调方法

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
   BOOL flag = [AoJiaoShareManager handleOpenUrl:url sourceApplication:sourceApplication];
    if (flag) {
        return YES;
    }

    
    return YES;
}

需要在URL Types 里配置相应id
identifler:com.weibo
identifler:weixin
identifler:tencent

调用

//分享
    [[AoJiaoShareManager sharedInstance]showWithTitle:@"魂器学院" image:@"https://img1.gtimg.com/10/1048/104857/10485731_980x1200_0.jpg" intro:@"魂器学院" url:@"https://img1.gtimg.com/10/1048/104857/10485731_980x1200_0.jpg" dataDic:nil];

以上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值