//
|
// UniversalSDK.m
|
// Unity-iPhone
|
//
|
// Created by 蔡瀚 on 2018/4/24.
|
//
|
|
#import "UniversalSDK.h"
|
#import "AdSupport/AdSupport.h"
|
#import "opus.h"
|
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
|
#import <UserNotifications/UserNotifications.h>
|
#endif
|
#import "SystemConfiguration/CaptiveNetwork.h"
|
#import <YYJPlatform/YYJPlatform.h>
|
|
@interface UniversalSDK()<UIWebViewDelegate>
|
@end
|
|
@implementation UniversalSDK
|
|
#define CHANNEL_NUM 1
|
|
static int s_frequency = 16000;
|
static int s_bitRate = 20000;
|
static int s_bandMode = OPUS_BANDWIDTH_WIDEBAND;
|
static int s_frameSize = 160;
|
static int sBatteryLevel = -1;
|
static int sBatteryState = -1;
|
static NSString* sAppID;
|
static NSString* sGameID;
|
static NSString* sUserName;
|
static NSThread* _thread;
|
|
static int initedState=0; //初始化状态,0初始化中,1成功,2失败
|
|
static NSString * const kClientID = @"185347479213-doi46trvoviu8l04tr5qe7uvbs6oelse.apps.googleusercontent.com";
|
|
-(void) Init
|
{
|
UIDevice *_device = [UIDevice currentDevice];
|
_device.batteryMonitoringEnabled = true;
|
|
NSString* _uniqueID = [[NSUserDefaults standardUserDefaults] objectForKey:@"tsw_unique_id"];
|
//获取IDFA
|
NSString* _idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
|
|
if(_uniqueID == NULL || [_uniqueID length] <= 0)
|
{
|
//判断IDFA是否为空
|
BOOL isEmpty = [[_idfa stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@"0" withString:@""].length;
|
if (isEmpty) {
|
//不为空,将IDFA作为唯一标识
|
_uniqueID = _idfa;
|
}
|
else {
|
//为空,获取UUID作为唯一标识
|
_uniqueID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
|
}
|
|
//保存唯一设备标识,如已存在则不进行任何处理
|
[[NSUserDefaults standardUserDefaults] setObject:_uniqueID forKey:@"tsw_unique_id"];
|
[[NSUserDefaults standardUserDefaults] synchronize];
|
}
|
|
// 取得UserAgent
|
UIWebView* _webView = [[UIWebView alloc] initWithFrame:CGRectZero];
|
NSString* _userAgent = [_webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
|
|
// 发送设备信息
|
NSMutableDictionary *_dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
|
_uniqueID,@"unique_id",
|
_idfa,@"android_id",
|
[NSNumber numberWithInt:S2U_DeviceInfo],@"code",
|
_userAgent,@"userAgent",nil];
|
[self SendMessageToUnity:_dict];
|
}
|
|
-(void)SendMessageToUnity:(NSDictionary*)dict
|
{
|
BOOL _result = [NSJSONSerialization isValidJSONObject:dict];
|
if(_result)
|
{
|
NSData* _jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
|
UnitySendMessage(UNITY_OBJ_NAME, UNITY_FUNC_NAME,
|
[[[NSString alloc] initWithData:_jsonData encoding:NSUTF8StringEncoding] UTF8String]);
|
}
|
}
|
|
-(void) BatteryThread {
|
while (TRUE)
|
{
|
[NSThread sleepForTimeInterval:1];
|
|
UIDevice *_device = [UIDevice currentDevice];
|
|
int _state = [_device batteryState];
|
if(_state != sBatteryState){
|
sBatteryState = _state;
|
NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
|
[NSNumber numberWithInt:sBatteryState], @"status",
|
[NSNumber numberWithInt:S2U_BatteryCharging], @"code", nil];
|
|
[self SendMessageToUnity:_dict];
|
}
|
|
int _level = (int)([_device batteryLevel] * 100);
|
if(_level != sBatteryLevel){
|
sBatteryLevel = _level;
|
NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
|
[NSNumber numberWithInt:sBatteryLevel], @"level",
|
[NSNumber numberWithInt:S2U_BatteryLevel], @"code", nil];
|
|
[self SendMessageToUnity:_dict];
|
}
|
}
|
}
|
|
-(void) OpenURL:(NSString*) url {
|
|
if(m_UIWebView != NULL) {
|
[self btnClick:NULL];
|
return;
|
}
|
|
CGRect _bounds = UnityGetMainWindow().bounds;
|
|
float _scale = _bounds.size.width / 1334;
|
|
float _width = 982 * _scale;
|
float _height = 560 * _scale;
|
|
float _offsetX = (_bounds.size.width - _width) * .5f;
|
float _offsetY = (_bounds.size.height - _height) * .5f;
|
|
m_UIWebView = [[UIWebView alloc] initWithFrame:CGRectMake(_offsetX, _offsetY, _width, _height)];
|
m_UIWebView.delegate = self;
|
m_UIWebView.scalesPageToFit = YES ;
|
m_UIWebView.scrollView.scrollEnabled = YES;
|
m_UIWebView.scrollView.bounces = NO;
|
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
|
[m_UIWebView loadRequest:request];
|
}
|
|
-(void) btnClick:(UIButton*)sender {
|
[m_CloseBtn removeFromSuperview];
|
[m_CloseBtn removeTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
|
m_CloseBtn = NULL;
|
|
NSURLCache *_cache = [NSURLCache sharedURLCache];
|
[_cache removeAllCachedResponses];
|
[_cache setDiskCapacity:0];
|
[_cache setMemoryCapacity:0];
|
|
[m_UIWebView removeFromSuperview];
|
m_UIWebView = NULL;
|
}
|
|
-(void)webViewDidStartLoad:(UIWebView *)webView{
|
}
|
|
-(void)webViewDidFinishLoad:(UIWebView *)webView{
|
|
[UnityGetMainWindow().rootViewController.view addSubview:m_UIWebView];
|
CGRect _bounds = UnityGetMainWindow().bounds;
|
|
float _scale = _bounds.size.width / 1334;
|
|
float _width = 982 * _scale;
|
float _height = 560 * _scale;
|
|
m_CloseBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
|
[m_CloseBtn setFrame:CGRectMake(_width - 455 * _scale, _height - 86 * _scale, 180 * _scale, 72 * _scale)];
|
[m_CloseBtn setTitle:@"我知道了" forState:UIControlStateNormal];
|
|
NSString *_bundlePath = [[NSBundle mainBundle] pathForResource:@"The2thWorldRES.bundle" ofType:nil];
|
NSBundle *_bundle = [NSBundle bundleWithPath:_bundlePath];
|
NSString *pic1Path = [_bundle pathForResource:@"TY_AN_34.png" ofType:nil];
|
|
[m_CloseBtn setBackgroundImage:[UIImage imageWithContentsOfFile:pic1Path] forState:UIControlStateNormal];
|
[m_CloseBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
|
[m_CloseBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
|
|
[m_UIWebView addSubview:m_CloseBtn];
|
}
|
|
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
|
}
|
|
-(void)QuickSDKInit:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
|
/*
|
初始化完成之后,会有初始化完成通知( yyj_PlatformInitDidFinishedNotification )开
|
发者在该回调⽅法中做登录操作
|
该通知应注册在初始化之前
|
*/
|
//添加⼀个初始化通知观察者,初始化结束后,登录等操作务必在收到该通知后调⽤
|
[[NSNotificationCenter defaultCenter]addObserver:self
|
selector:@selector(YYJPlatformInitFinished)
|
name:yyj_PlatformInitDidFinishedNotification object:nil];
|
//初始化失败
|
[[NSNotificationCenter defaultCenter]addObserver:self
|
selector:@selector(YYJPlatformInitFinished)
|
name:yyj_PlatformInitFinishedFailNotification object:nil];
|
//添加⼀个登录成功通知观察者,调⽤悬浮框等操作务必在收到该通知后调⽤
|
[[NSNotificationCenter defaultCenter]addObserver:self
|
selector:@selector(YYJPlatformLogin) name:yyj_PlatformLoginNotification
|
object:nil];
|
//添加⼀个注销成功通知观察者
|
[[NSNotificationCenter defaultCenter]addObserver:self
|
selector:@selector(YYJPlatformLogout) name:yyj_PlatformLogoutNotification
|
object:nil];
|
// 添加⼀个⽀付成功通知观察者
|
[[NSNotificationCenter defaultCenter]addObserver:self
|
selector:@selector(YYJPlatformBMaiSuccessful)
|
name:yyj_PlatformBMaiSuccessfulNotification object:nil];
|
// 添加⼀个⽀付失败通知观察者
|
[[NSNotificationCenter defaultCenter]addObserver:self
|
selector:@selector(YYJPlatformBMaiFail) name:yyj_PlatformBMaiFailNotification
|
object:nil];
|
//添加⼀个实名认证⻚⾯关闭通知观察者
|
// [[NSNotificationCenter defaultCenter]addObserver:self
|
// selector:@selector(YYJPlatformRealNameAuthenticationClose)
|
// name:yyj_PlatformRealNameAuthenticationCloseNotification object:nil];
|
#ifdef DEBUG
|
// 输出⽇志
|
[[YYJPlatform yyj_defaultPlatform]yyj_isShowLog:YES];
|
#endif
|
[[YYJPlatform yyj_defaultPlatform] yyj_AppsFlyer_Init:AF_KEY appleAppID:AF_APPLE_APPID];
|
[self initYYJSdk];
|
}
|
|
-(void) initYYJSdk{
|
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
|
NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
|
// SDK初始化,务必放在其他接⼝调⽤之前
|
[[YYJPlatform yyj_defaultPlatform]yyj_initializeWithAppId: YYJ_APPID gameVersion:app_Version appScheme: YYJ_APPSCHEME];
|
initedState=0;
|
}
|
|
- (void)YYJPlatformInitFinished{
|
NSLog(@"渠道初始化成功");
|
initedState=1;
|
NSMutableDictionary *_dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
|
[NSNumber numberWithInt:S2U_SdkInitComplete], @"code",
|
@"sanxia", @"channelPlatform", nil];
|
[self SendMessageToUnity:_dict];
|
}
|
|
|
- (void)YYJPlatformInitFinishedFail{
|
NSLog(@"渠道初始化失败");
|
initedState=2;
|
}
|
|
- (void)YYJPlatformLogin {
|
NSString *regType = [[YYJPlatform yyj_defaultPlatform] yyj_regType];
|
if(regType&&[regType length]!=0){
|
NSLog(@"渠道注册成功");
|
NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
|
regType, @"reg_type",
|
[NSNumber numberWithInt:S2U_FreePlatformRegisterOk], @"code", nil];
|
[self SendMessageToUnity:_dict];
|
}else{
|
NSLog(@"渠道登录成功");
|
NSString *account = [[YYJPlatform yyj_defaultPlatform] yyj_userUID];
|
NSString *game_id = [[YYJPlatform yyj_defaultPlatform] yyj_gameId];
|
NSString *session_id = [[YYJPlatform yyj_defaultPlatform] yyj_token];
|
|
NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
|
[NSDictionary dictionaryWithObjectsAndKeys:account, @"account",
|
game_id, @"game_id",
|
session_id, @"session_id", nil],@"info",
|
[NSNumber numberWithInt:S2U_FreePlatformLoginOk], @"code", nil];
|
[self SendMessageToUnity:_dict];
|
}
|
[[YYJPlatform yyj_defaultPlatform]yyj_showFloatWindow]; //显示悬浮窗
|
}
|
|
- (void)YYJPlatformLogout {
|
NSLog(@"渠道注销成功");
|
NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:S2U_FreePlatformLogoutOk], @"code", nil];
|
[self SendMessageToUnity:_dict];
|
}
|
|
- (void)YYJPlatformBMaiSuccessful{
|
NSLog(@"渠道支付成功");
|
NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
|
[NSNumber numberWithInt:S2U_FreePlatformPayOk], @"code", nil];
|
[self SendMessageToUnity:_dict];
|
}
|
|
- (void) YYJPlatformBMaiFail{
|
NSLog(@"渠道支付失败");
|
NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
|
[NSNumber numberWithInt:S2U_FreePlatformPayFail], @"code", nil];
|
[self SendMessageToUnity:_dict];
|
}
|
|
-(id) APNativeJSONObject:(NSData *)data{
|
if (!data) {
|
return nil;
|
}
|
|
NSError *error = nil;
|
id retId = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
|
|
if (error) {
|
NSLog(@"%s trans data to obj with error: %@", __func__, error);
|
return nil;
|
}
|
|
return retId;
|
}
|
|
-(void) PlatformLogin{
|
switch (initedState) {
|
case 0:
|
{
|
|
}
|
break;
|
case 1:
|
[[YYJPlatform yyj_defaultPlatform]yyj_userLogin];
|
break;
|
case 2:
|
[self initYYJSdk];
|
break;
|
default:
|
break;
|
}
|
}
|
|
-(void)HandleUnityMessage:(NSString *)json {
|
|
NSLog(@"收到Unity发来的消息 => %@", json);
|
|
NSData *_jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
|
NSDictionary *_dict = [self APNativeJSONObject:_jsonData];
|
|
switch([[_dict objectForKey:@"code"] intValue]){
|
case U2S_Init:
|
sAppID = _dict[@"appID"];
|
sGameID = _dict[@"gameID"];
|
[self Init];
|
break;
|
case U2S_CopyContent:
|
[UIPasteboard generalPasteboard].string = _dict[@"content"];
|
break;
|
case U2S_FreePlatformInit:
|
break;
|
case U2S_MakeKeyAndVisible:
|
{
|
UIWindow * _window = [[UIApplication sharedApplication].delegate window];
|
if (_window != nil && _window.rootViewController != nil) {
|
[_window makeKeyAndVisible];
|
}
|
}
|
break;
|
case U2S_OpenWebView:
|
[self OpenURL:_dict[@"url"]];
|
break;
|
case U2S_FreePlatformLogin:
|
[self PlatformLogin];
|
break;
|
case U2S_FreePlatformLogout:
|
{
|
[[YYJPlatform yyj_defaultPlatform]yyj_userLogout];
|
}
|
break;
|
case U2S_CreateRole:
|
{
|
// 更新角色信息
|
NSString *serverName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"serverName"]];
|
NSString *gameRoleName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleName"]];
|
NSString *serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]];
|
NSString *gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
|
NSString *gameUserLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"level"]];
|
|
[[YYJPlatform yyj_defaultPlatform]yyj_submitRoleInfoWithServerid:serverId andServerName:serverName andCharid:gameRoleID andRoleName:gameRoleName andRolelevel:gameUserLevel];
|
break;
|
}
|
case U2S_RoleLogin:
|
{
|
// 更新角色信息
|
NSString *serverName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"serverName"]];
|
NSString *gameRoleName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleName"]];
|
NSString *serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]];
|
NSString *gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
|
NSString *gameUserLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"level"]];
|
|
[[YYJPlatform yyj_defaultPlatform]yyj_submitRoleInfoWithServerid:serverId andServerName:serverName andCharid:gameRoleID andRoleName:gameRoleName andRolelevel:gameUserLevel];
|
break;
|
}
|
|
case U2S_RoleLevelUp:
|
{
|
// 更新角色信息
|
NSString *serverName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"serverName"]];
|
NSString *gameRoleName = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleName"]];
|
NSString *serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]];
|
NSString *gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
|
NSString *gameUserLevel = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"level"]];
|
|
[[YYJPlatform yyj_defaultPlatform]yyj_submitRoleInfoWithServerid:serverId andServerName:serverName andCharid:gameRoleID andRoleName:gameRoleName andRolelevel:gameUserLevel];
|
break;
|
}
|
case U2S_FreePlatformPay:
|
{
|
NSString *serverId = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"sid"]];
|
NSString *gameRoleID = [NSString stringWithFormat:@"%@",[_dict objectForKey:@"roleID"]];
|
NSString *goodsID = [NSString stringWithFormat:@"%@", [_dict objectForKey:@"cpInfo"]];
|
NSString *productName = [NSString stringWithFormat:@"%@", [_dict objectForKey:@"title"]];
|
NSString *mount = [NSString stringWithFormat:@"%@", [_dict objectForKey:@"mount"]];
|
NSString *orderId = [NSString stringWithFormat:@"%@", [_dict objectForKey:@"orderId"]];
|
NSString *_appid = sAppID;
|
NSString *extrasParams = [NSString stringWithFormat:@"{\"appid\":\"%@\",\"cpinfo\":\"%@\",\"cporderid\":\"%@\"}",
|
_appid,
|
[_dict objectForKey:@"cpInfo"],
|
[_dict objectForKey:@"orderId"]
|
];
|
[[YYJPlatform yyj_defaultPlatform] yyj_BMaiWithMoney:mount productID:goodsID productName:productName charId:gameRoleID serverId:serverId expandInfo:extrasParams cporderId:orderId];
|
break;
|
}
|
case U2S_BatteryListenStart:
|
if(_thread == NULL)
|
{
|
_thread = [[NSThread alloc] initWithTarget:self selector:@selector(BatteryThread) object:nil];
|
[_thread setName:@"BatteryCheck"];
|
}
|
if(![_thread isExecuting])
|
{
|
[_thread start];
|
}
|
break;
|
case U2S_BatteryListenStop:
|
break;
|
}
|
}
|
@end
|
|
extern "C" void native_opus_init(int frequency, int bitRate, int bandMode)
|
{
|
s_frequency = frequency;
|
s_bandMode = bandMode;
|
s_bitRate = bitRate;
|
s_frameSize = frequency / 100;
|
}
|
|
extern "C" int native_opus_encode(opus_int16 *pcm, int len, unsigned char *opus)
|
{
|
int errorCode = 0;
|
opus_int32 skip = 0;
|
OpusEncoder *enc = opus_encoder_create(s_frequency, CHANNEL_NUM, OPUS_APPLICATION_VOIP, &errorCode);
|
if (OPUS_OK != errorCode) {
|
enc = NULL;
|
return -1;
|
}
|
|
opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(s_bandMode));
|
opus_encoder_ctl(enc, OPUS_SET_BITRATE(s_bitRate));
|
opus_encoder_ctl(enc, OPUS_SET_VBR(1));
|
opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(10));
|
opus_encoder_ctl(enc, OPUS_SET_INBAND_FEC(0));
|
opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(OPUS_SIGNAL_VOICE));
|
opus_encoder_ctl(enc, OPUS_SET_DTX(0));
|
opus_encoder_ctl(enc, OPUS_SET_PACKET_LOSS_PERC(0));
|
opus_encoder_ctl(enc, OPUS_GET_LOOKAHEAD(&skip));
|
opus_encoder_ctl(enc, OPUS_SET_LSB_DEPTH(16));
|
|
unsigned char *rbytes = opus;
|
opus_int16 *frame = pcm;
|
int totalSize = 0;
|
while (len >= s_frameSize)
|
{
|
opus_int32 length = opus_encode(enc, frame, s_frameSize, rbytes + sizeof(char), s_bitRate);
|
rbytes[0] = length;
|
frame += s_frameSize;
|
rbytes += length + sizeof(char);
|
len -= s_frameSize;
|
totalSize += length;
|
}
|
opus_encoder_destroy(enc);
|
return totalSize;
|
}
|
|
extern "C" int native_opus_decode(unsigned char *opus, int len, short *pcm)
|
{
|
int err = 0;
|
//opus_int32 skip = 0;
|
|
OpusDecoder *dec = opus_decoder_create(s_frequency, CHANNEL_NUM, &err);
|
if (err != OPUS_OK) {
|
dec = NULL;
|
return -1;
|
}
|
|
while (len > 0)
|
{
|
int frame_opus_length = opus[0];
|
int length = opus_decode(dec, opus + sizeof(char), frame_opus_length, pcm, s_frameSize, 0);
|
opus += sizeof(char) + frame_opus_length;
|
pcm += s_frameSize;
|
len = len - frame_opus_length - sizeof(char);
|
}
|
opus_decoder_destroy(dec);
|
return 0;
|
}
|