Weex开发Weex开发技巧weex社区

WEEX调用QQ登录,分享原生SDK遇到的问题

2018-04-20  本文已影响121人  行业碧油鸡
平台就有QQ开放平台和QQ互联,由于QQ原生SDK文档很少又乱,如果导入不熟悉的话建议下载其Demo。在网站注册啊,填写连个URL Scheme啊,就不说了,遇到问题请谷歌!
接下来就是和原生一样的配置函数:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url;
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    CLog(@"fml url -> %@",url);
    if ([url.scheme isEqualToString:kWechatAppID]) {
        FMLLoginShareModule *urlHandler = [[FMLLoginShareModule alloc] init];
        return [WXApi handleOpenURL:url delegate:(id<WXApiDelegate>)urlHandler];
    }
    else if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",kQQAppID]]) {
        // 授权
        return [TencentOAuth HandleOpenURL:url];
    }
    else if ([url.scheme isEqualToString:@"QQ690C8423"]) {
        // 分享
        FMLLoginShareModule *urlHandler = [[FMLLoginShareModule alloc] init];
        return [QQApiInterface handleOpenURL:url delegate:(id<QQApiInterfaceDelegate>)urlHandler];
    }
    else {
        return YES;
    }
}
在我们创建的 FMLLoginShareModule类中去处理相应的功能:
首先在 FMLLoginShareModule.h中配置:
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>

@interface FMLLoginShareModule : NSObject<WXModuleProtocol, TencentLoginDelegate, TencentSessionDelegate, QQApiInterfaceDelegate>

@end
然后在 FMLLoginShareModule.m中:
@interface FMLLoginShareModule ()

@property (nonatomic, retain) TencentOAuth *tencentOAuth;
@property (nonatomic, copy) NSArray *permissions;
@property (nonatomic, strong) NSMutableDictionary *resultDict;

@property (nonatomic, copy) WXModuleKeepAliveCallback qqCallBack;

@end

@implementation FMLLoginShareModule

@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(qqLogin:))
WX_EXPORT_METHOD(@selector(qqLogout:))
WX_EXPORT_METHOD(@selector(isQQLogined:))
WX_EXPORT_METHOD(@selector(isQQInstalled:))
WX_EXPORT_METHOD(@selector(getQQUserInfo:))
WX_EXPORT_METHOD(@selector(shareToQzone::::))
WX_EXPORT_METHOD(@selector(shareToQQ::::))
- (void)qqLogin:(WXModuleKeepAliveCallback)callback {
    self.qqCallBack = callback;
    
    if ([QQApiInterface isQQInstalled]) {
        // 如果已经授权过,先将保存在本地的access_token,openid,expirationDate配置给我们的tencentOAuth
        [self confiureTencentOAuth];
      // 判断登录态
        BOOL isLogin = [self.tencentOAuth isSessionValid];
        if (isLogin && [FMLCommonUtilities isNonnull:self.tencentOAuth.openId]) {
            [self.resultDict setObject:self.tencentOAuth.accessToken forKey:@"access_token"];
            [self.resultDict setObject:[self.tencentOAuth openId] forKey:@"openid"];

            // 如果已经授权了,直接去获取用户信息
            [self.tencentOAuth getUserInfo];

            // 直接回调给weex页面
            if (nil != self.qqCallBack)
            {
                [self.resultDict setValue:@"0" forKey:@"r"];
                self.qqCallBack(self.resultDict, NO);
            }
            CLog(@"fml 已经授权登录 tencentOAuth -> %@", self.resultDict);
        }
        else {
            // 未授权或者授权失效,重新授权
            self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:kQQAppID andDelegate:self];
            self.tencentOAuth.authShareType = AuthShareType_QQ;
            self.tencentOAuth.authMode = kAuthModeClientSideToken;
            [self.tencentOAuth authorize:self.permissions
                              localAppId:kQQAppID
                                inSafari:NO];
        }
    }
    else {
        CLog(@"未安装QQ");
        if (nil != self.qqCallBack)
        {
            [self.resultDict setValue:@"-1" forKey:@"r"];
            [self.resultDict setValue:@"未安装QQ" forKey:@"msg"];
            self.qqCallBack(self.resultDict, NO);
        }
    }
}
/**
 * 退出登录(退出登录后,TecentOAuth失效,需要重新初始化)
 * \param delegate 第三方应用用于接收请求返回结果的委托对象
 */
- (void)logout:(id<TencentSessionDelegate>)delegate;

logout回调:

/**
 * 退出登录的回调
 */
- (void)tencentDidLogout;
/**
 * 判断登录态是否有效
 * \return 处理结果,YES表示有效,NO表示无效,请用户重新登录授权
 */
- (BOOL)isSessionValid;
/**
 * 获取用户个人信息
 * \return 处理结果,YES表示API调用成功,NO表示API调用失败,登录态失败,重新登录
 */
- (BOOL)getUserInfo;

getUserInfo 回调:

//获取QQ用户信息
- (void)getUserInfoResponse:(APIResponse*)response {
    // 在这个地方我们可以获取授权用户的信息
    if (response && response.retCode == URLREQUEST_SUCCEED) {
        NSDictionary *dict = [response jsonResponse];
        
        //  do something here
            
        CLog(@"fml 获取用户信息成功 -> %@", dict);
    } else {
        CLog(@"获取用户信息失败");
    }
}
static NSString * const kFMLLoginShareModuleEventShareToQQEvent = @"shareToQQEvent";

#pragma mark - QQ分享
- (void)shareToQQ:(NSString *)title
                 :(NSString *)description
                 :(NSString *)targetUrl
                 :(NSString *)imageUrl
{
    
    [FMLStorageManager storeStringWithTableName:kFMLAccountTableKey
                                          ByKey:kFMLLoginShareModuleEventKey
                                          value:kFMLLoginShareModuleEventShareToQQEvent];
    
    QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:targetUrl]
                                                        title:title
                                                  description:description
                                              previewImageURL:[NSURL URLWithString:imageUrl]];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
    //将内容分享到qq
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    CLog(@"fml QQApiSendResultCode -> %d",sent);
}

分享回调(微信分享,微信登录,QQ分享回调都是这个方法):

- (void)onResp:(BaseResp *)resp
{
    CLog(@"BaseResp结果:%@", resp.description);
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *response = (SendAuthResp *)resp;
        CLog(@"code:%@,state:%@", response.code, response.state);
        switch (resp.errCode) {
            case 0:
            {
                //成功 code:用户换取access_token的code,仅在ErrCode为0时有效
                
            }
                break;
            case -4:
            {
                //用户拒绝授权
                CLog(@"用户拒绝授权");
            }
                break;
            case -2:
            {
                //用户取消
                CLog(@"用户取消登录");
            }
                break;
            default: {
                CLog(@"登录失败");
                }
                break;
        }
    }
    else if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        //微信终端向第三方程序返回的SendMessageToWXReq处理结果。
        SendMessageToWXResp *response = (SendMessageToWXResp*)resp;
        CLog(@"SendMessageToWXResp:%d %d", response.errCode, response.type);
        if (response.errCode == 0) {
            CLog(@"微信分享成功");
            }
        else{
            CLog(@"微信分享失败");
            }
    }
    else if([resp isKindOfClass:[SendMessageToQQResp class]])
    {
        //qq终端向第三方程序返回的SendMessageToQQReq处理结果。
        SendMessageToQQResp* sendResp = (SendMessageToQQResp*)resp;
        CLog(@"SendMessageToQQResp:%@ %d", sendResp.result,sendResp.type);
        
        if ([sendResp.result isEqualToString:@"0"]) {
            CLog(@"QQ分享成功");
            
            [self.resultDict setValue:@"0" forKey:@"r"];
            
            NSString *eventName = [FMLStorageManager obtainStringWithTableName:kFMLAccountTableKey
                                                                         ByKey:kFMLLoginShareModuleEventKey];
            if ([FMLCommonUtilities isNonnull:eventName]) {
                [self fml_fireGlobalEvent:eventName params:self.resultDict];
            }
        }
        else if ([sendResp.result isEqualToString:@"-4"]) {
            CLog(@"取消qq分享");
            
            [self.resultDict setValue:@"-1" forKey:@"r"];
            [self.resultDict setValue:@"取消qq分享" forKey:@"msg"];
            
            NSString *eventName = [FMLStorageManager obtainStringWithTableName:kFMLAccountTableKey
                                                                         ByKey:kFMLLoginShareModuleEventKey];
            if ([FMLCommonUtilities isNonnull:eventName]) {
                [self fml_fireGlobalEvent:eventName params:self.resultDict];
            }
        }
        else {
            CLog(@"QQ分享失败");
            [self.resultDict setValue:@"-1" forKey:@"r"];
            [self.resultDict setValue:@"QQ分享失败" forKey:@"msg"];
            NSString *eventName = [FMLStorageManager obtainStringWithTableName:kFMLAccountTableKey
                                                                         ByKey:kFMLLoginShareModuleEventKey];
            if ([FMLCommonUtilities isNonnull:eventName]) {
                [self fml_fireGlobalEvent:eventName params:self.resultDict];
            }
        }
    }
}

由于当微信分享,QQ分享或者微信登录返回并回调- (void)onResp:(BaseResp *)resp方法的时候,该module已经被销毁,对应的callback,weexInstance自然会被销毁。这个时候我们要回调WEEX就需要通过fireGlobalEvent全局事件:

/**
 * fire global event
 */
- (void)fireGlobalEvent:(NSString *)eventName params:(NSDictionary *)params;

但是weexInstance已经被销毁,我们需要weex调用module原生方法的时候保存weexInstanceinstanceId。然后通过通知回调:

- (void)fml_fireGlobalEvent:(NSString *)eventName
                     params:(NSDictionary *)params {
    if (self.weexInstance && [FMLCommonUtilities isNonnull:self.weexInstance.instanceId]) {
        [[self weexInstance] fireGlobalEvent:eventName params:params];
    }
    else {
           NSString *weexinstanceId = [FMLStorageManager obtainStringWithTableName:kFMLAccountTableKey ByKey:kFMLWeexInstanceKey];
        if ([FMLCommonUtilities isNonnull:weexinstanceId] && [weexinstanceId isNotBlank]) {
            NSDictionary * userInfo = @{
                                        @"weexInstance":weexinstanceId,
                                        @"param":params
                                        };
            [[NSNotificationCenter defaultCenter] postNotificationName:eventName
                                                                object:self
                                                              userInfo:userInfo];
        }
    }
}

在WEEX页面监听对应的全局事件:

mounted: function () {
      var self = this
      var globalEvent = weex.requireModule('globalEvent');
      globalEvent.addEventListener("shareToQQEvent", function (ret) {
            if (0 == ret.r){
                console.log("JS QQ分享给好友 成功 -> "+ret.r)
                modal.alert({
                    message: "成功分享给QQ好友 ",
                    okTitle: 'ok'
                    })
            }
            else if (-1 == ret.r) {
              console.log("JS QQ分享给好友 失败 ->"+ret.msg)
              modal.alert({
                    message: "QQ分享给好友失败, " + ret.msg,
                    okTitle: 'ok'
                    })
            }
      });
}
上一篇下一篇

猜你喜欢

热点阅读