基于react native的原生iOS 微信登录


微信open SDK

环境

RN@0.73.6 React@18.2 XCode@15.3

引入SDK:WechatOpenSDK-XCFramework.xcframework

xcode配置请按照ios接入指南

ios 创建CustomerWxLogin类

CustomerWxLogin.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBridgeModule.h>
#import <WXApi.h>

@interface CustomerWxLogin : RCTEventEmitter <RCTBridgeModule, WXApiDelegate>

@end

CustomerWxLogin.m

#import "CustomerWxLogin.h"
#import "WXApiObject.h"
#import <React/RCTEventDispatcher.h>
#import <React/RCTBridge.h>
#import <React/RCTLog.h>

#define APP_ID @"wx"
#define UNIVERSAL_LINK @"https://xxx.com/"

@implementation CustomerWxLogin

#define NOT_REGISTERED (@"registerApp required.")
#define INVOKE_FAILED (@"WeChat API invoke returns false.")

RCT_EXPORT_MODULE();

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:@"RCTOpenURLNotification" object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)handleOpenURL:(NSNotification *)aNotification
{
    NSString * aURLString =  [aNotification userInfo][@"url"];
    NSURL * aURL = [NSURL URLWithString:aURLString];

    if ([WXApi handleOpenURL:aURL delegate:self])
    {
        return YES;
    } else {
        return NO;
    }
}

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

+ (BOOL)requiresMainQueueSetup {
    return YES;
}

//微信登陆
RCT_EXPORT_METHOD(sendAuthRequest:(NSString *)scope
                  :(NSString *)state
                  :(RCTResponseSenderBlock)callback)
{
   // 注册微信
   [WXApi registerApp:APP_ID universalLink:UNIVERSAL_LINK];
  
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope = scope;
    req.state = state;
  
    [WXApi sendReq:req completion:^(BOOL success) {
      callback(@[success ? [NSNull null] : INVOKE_FAILED]);
    }];
}


#pragma mark - wx callback


-(void) onResp:(BaseResp*)resp
{
    if ([resp isKindOfClass:[SendAuthResp class]]) {
      SendAuthResp *authResp = (SendAuthResp *)resp;
      NSString *authCode = authResp.code;
      [self sendEventWithName:@"WxLoginSuccess" body:@{@"code": authCode}];
    }
}

@end

react native端调用

创建wxLogin.js用于架起桥梁连接ios原生代码

import { NativeEventEmitter, NativeModules } from 'react-native';

let { WeChat, CustomerWxLogin } = NativeModules;

if (WeChat == null) {
    WeChat = CustomerWxLogin;
}

const WeChatEmitter = new NativeEventEmitter(WeChat);

/**
 * @method sendAuthRequest
 * @param {Array} scopes - the scopes for authentication.
 * @return {Promise}
 */
export function sendAuthRequest(scopes, state) {
    return new Promise((resolve, reject) => {
        WeChat.sendAuthRequest(scopes, state, () => {
            WeChatEmitter.addListener('WxLoginSuccess', (events) => {
                resolve(events)
            })

        });

    });
}

配置AppDelegate.h

#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import "WXApi.h"

@interface AppDelegate : RCTAppDelegate<WXApiDelegate>

@end

AppDelegate.mm

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTLinkingManager.h>

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"BanDaiMatch";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
  return [self getBundleURL];
}

- (NSURL *)getBundleURL
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

//weixin
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application
  continueUserActivity:(NSUserActivity *)userActivity
  restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable
  restorableObjects))restorationHandler {
  // 触发回调方法
  [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
  return [WXApi handleOpenUniversalLink:userActivity
  delegate:self];
}


@end

在页面中使用

import * as WeChat from '../../common/js/wxLogin';

//微信授权登录
      WeChat.sendAuthRequest('snsapi_userinfo', 'wechat_sdk_demo').then(response => {
        console.log("[处理授权登录后的结果]", response.code)
        
      })
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值