iOS static
此篇是為了註記iOS static
需求
因為是希望把跟server註冊APNs token這段拿到React Native JS Code這邊做掉,所以需要APNs token的取得和通知(當token更新或者其他原因更換了..得通知到JS Code) ps.這裡的通知就是上方的寫法內容
因為怕ios Native已取得token,而後JS Code才監聽(addListener)完成,所以這邊為了保險一點,在iOS Native內加上static參數去儲存token,並且在App第一次開啟時先去獲取一次該static token
還有加上EventEmitter測試的Code
完整Code如下
APNsTokenEmitter.h
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
@interface APNsTokenEmitter : RCTEventEmitter<RCTBridgeModule>
@property (nonatomic, retain) NSString *apnsToken;
- (void)apnsTokenReceive:(NSString *)token;
@endAPNsTokenEmitter.m
#import "APNsTokenEmitter.h"
#import <React/RCTLog.h>
@implementation APNsTokenEmitter
{
bool hasListeners;
}
RCT_EXPORT_MODULE();
@synthesize apnsToken;
/**
想再其它.m檔內使用,得先取得APNsTokenEmitter,但用下方方法初始化會有Error
APNsTokenEmitter * tokenEmitter = [[APNsTokenEmitter alloc] init];
請參考 https://github.com/facebook/react-native/issues/15421 解法(singleton pattern)
**/
+ (id)allocWithZone:(NSZone *)zone {
static APNsTokenEmitter *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [super allocWithZone:zone];
});
return sharedInstance;
}
-(NSArray<NSString *> *)supportedEvents
{
return @[@"APNsToken"];
}
// Will be called when this module's first listener is added.
-(void)startObserving {
RCTLogInfo(@"APNsTokenEmitter startObserving");
hasListeners = YES;
// Set up any upstream listeners or background tasks as necessary
}
// Will be called when this module's last listener is removed, or on dealloc.
-(void)stopObserving {
RCTLogInfo(@"APNsTokenEmitter stopObserving");
hasListeners = NO;
// Remove upstream listeners, stop unnecessary background tasks
}
-(void)apnsTokenReceive:(NSString *)token
{
self.apnsToken = token;
if (hasListeners) {
[self sendEventWithName:@"APNsToken" body:token];
RCTLogInfo(@"APNsTokenEmitter apnsTokenReceive(Has Listener), %@", token);
}else {
RCTLogInfo(@"APNsTokenEmitterapnsTokenReceive(No Listener), %@", token);
}
}
@endAppDelegat.h
AppDelegat.m(內包含註冊APNs token的code,詳細還是參考註冊那篇文章)
AllPayPassMethod.h (這是我曝露給RN Code的Module)
AllPayPassMethod.m
RN JS Code (只貼部分code)
Last updated