少年修仙传客户端基础资源
Assets/Plugins/iOS/The2thWorldSDK/UniversalSDK.mm
@@ -9,11 +9,13 @@
#import "FreeSDK.h"
#import "JPUSHService.h"
#import "AdSupport/AdSupport.h"
#import "Tracking.h"
#import "opus.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "SystemConfiguration/CaptiveNetwork.h"
#import <TTTracker/TTTracker+Game.h>
@interface UniversalSDK()<JPUSHRegisterDelegate>
@end
@@ -28,28 +30,95 @@
static int s_frameSize = 160;
static int sBatteryLevel = -1;
static int sBatteryState = -1;
static NSThread * _thread;
-(void) MakeKeyAndVisible {
    UIWindow * _window = [[UIApplication sharedApplication].delegate window];
    if (_window != nil && _window.rootViewController != nil) {
        [_window makeKeyAndVisible];
-(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];
    // 自由sdk初始化
    [self FreeSDKInit];
    // 发送个推id
    [_dict removeAllObjects];
    [_dict setObject:[JPUSHService registrationID] forKey:@"clientID"];
    [_dict setObject:[NSNumber numberWithInt:S2U_PushClientID] forKey:@"code"];
    [self SendMessageToUnity:_dict];
    // 热云初始化
    [Tracking initWithAppKey:@"3c3724431309474be938e0b64d4ad74f" withChannelId:@"_default_"];
    // 今日头条
    [TTTracker startWithAppID:@"151709" channel:@"ios-snqxz" appName:@"少年奇侠传"];
    // 发送初始化完成
    [_dict removeAllObjects];
    [_dict setObject:[NSNumber numberWithInt:S2U_SdkInitComplete] forKey:@"code"];
    [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) FreeSDKInit {
    [FreeSDK initSDKWithAppId:FreeSDK_AppID withSDKBlock:^(YLSDKType type, NSString *msg) {
        NSLog(@"The2thWorldSDK => %@", msg);
        NSMutableDictionary *_dict = NULL;
        switch (type) {
            case YLSDKTypeInitSuccess:
            {
                NSString *_jsonString = [NSString stringWithFormat:@"{\"code\":%d}",CODE_SDK_FREEPLATFORM_INIT_OK];
                UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_jsonString UTF8String]);
                _dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithInt:S2U_FreePlatformInitOk],@"code",nil];
                [self SendMessageToUnity:_dict];
            }
                break;
            case YLSDKTypeInitFailure:
            {
                NSString *_jsonString = [NSString stringWithFormat:@"{\"code\":%d}",CODE_SDK_FREEPLATFORM_INIT_FAIL];
                UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_jsonString UTF8String]);
                _dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithInt:S2U_FreePlatformInitFail],@"code",nil];
                [self SendMessageToUnity:_dict];
            }
                break;
            case YLSDKTypeSwitchAccount:
@@ -58,39 +127,24 @@
                break;
            case YLSDKTypePaySuccess:
            {
                NSString *_jsonString = [NSString stringWithFormat:@"{\"code\":%d}",CODE_SDK_FREEPLATFORM_PAY_OK];
                UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_jsonString UTF8String]);
                _dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithInt:S2U_FreePlatformPayOk],@"code",nil];
                [self SendMessageToUnity:_dict];
            }
                break;
            case YLSDKTypePayFailed:
            {
                NSString *_jsonString = [NSString stringWithFormat:@"{\"code\":%d}",CODE_SDK_FREEPLATFORM_PAY_FAIL];
                UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_jsonString UTF8String]);
                _dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithInt:S2U_FreePlatformPayFail],@"code",nil];
                [self SendMessageToUnity:_dict];
            }
                break;
        }
    }];
    
    UIDevice *_device = [UIDevice currentDevice];
    _device.batteryMonitoringEnabled = true;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FreeSDKLoginOK) name:YLUserDidLoginNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FreeSDKCancelLogin) name:YLUserDidCancelLoginNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FreeSDKRegisterOK) name:YLUserDidSignUpNotification object:nil];
    // 个推id发送
    NSString *_content = [NSString stringWithFormat:@"{\"code\":%d,\"clientID\":\"%@\"}",CODE_SDK_GETUI_CLIENT_ID,[JPUSHService registrationID]];
    UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_content UTF8String]);
    // 电池监控
    NSThread * _thread = [[NSThread alloc] initWithTarget:self selector:@selector(BatteryThread) object:nil];
    [_thread setName:@"BatteryCheck"];
    [_thread start];
    //[self GetUniqueID];
//    [self GetIDFA];
//    [self GetUserAgent];
//    [self GetIPAddress];
}
-(void) BatteryThread {
@@ -102,50 +156,54 @@
        
        int _state = [_device batteryState];
        if(_state != sBatteryState){
            NSLog(@"The2thWorldSDK => 电池状态发生了改变: %d",_state);
            sBatteryState = _state;
            NSString *_content = [NSString stringWithFormat:@"{\"code\":%d,\"status\":%d}",CODE_SDK_BATTERY_STATE_CHANGED,sBatteryState];
            UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_content UTF8String]);
            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){
            NSLog(@"The2thWorldSDK => 电池电量发生了改变: %d",_level);
            sBatteryLevel = _level;
            NSString *_content = [NSString stringWithFormat:@"{\"code\":%d,\"level\":%d,\"scale\":100}",CODE_SDK_BATTERY_LEVEL_CHANGED,sBatteryLevel];
            UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_content UTF8String]);
            NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:sBatteryLevel], @"level",
                                   [NSNumber numberWithInt:S2U_BatteryLevel], @"code", nil];
            [self SendMessageToUnity:_dict];
        }
    }
}
-(void) FreeSDKRegisterOK {
-(void) FreeSDKRegisterOK
{
    YLAccount *_account = [YLAccount sharedInstance];
    NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                           _account.token, @"token",
                           [NSString stringWithFormat:@"%f",[_account.tokenExpiry timeIntervalSince1970]], @"token_expire",
                           [NSNumber numberWithLong:_account.accountId], @"account_id",
                           _account.identifier, @"account",
                           [NSNumber numberWithInt:S2U_FreePlatformRegisterOk], @"code", nil];
    [self SendMessageToUnity:_dict];
    
    NSString *_jsonString = [NSString stringWithFormat:@"{\"code\":%d,\"token\":\"%@\",\"token_expire\":\"%ld\",\"account_id\":\"%ld\",\"account\":\"%@\",\"phone\":\"%ld\"}",
                             CODE_SDK_FREEPLATFORM_REG_OK,
                             _account.token,
                             (long)[_account.tokenExpiry timeIntervalSince1970],
                             (long)_account.accountId,
                             _account.identifier,
                             (long)_account.hasBindPhone];
    [Tracking setRegisterWithAccountID:_account.identifier];
    
    UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_jsonString UTF8String]);
    [TTTracker registerEventByMethod:@"freesdk" isSuccess:YES];
}
-(void) FreeSDKLoginOK {
-(void) FreeSDKLoginOK
{
    YLAccount *_account = [YLAccount sharedInstance];
    NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                           [NSDictionary dictionaryWithObjectsAndKeys:_account.token, @"token",
                            [NSString stringWithFormat:@"%f",[_account.tokenExpiry timeIntervalSince1970]], @"token_expire",
                            [NSNumber numberWithLong:_account.accountId], @"account_id",
                            _account.identifier, @"account", nil],@"info",
                           [NSNumber numberWithInt:S2U_FreePlatformLoginOk], @"code", nil];
    [self SendMessageToUnity:_dict];
    
    NSString *_jsonString = [NSString stringWithFormat:@"{\"code\":%d,\"token\":\"%@\",\"token_expire\":\"%ld\",\"account_id\":\"%ld\",\"account\":\"%@\",\"phone\":\"%ld\"}",
                             CODE_SDK_FREEPLATFORM_LOGIN_OK,
                             _account.token,
                             (long)[_account.tokenExpiry timeIntervalSince1970],
                             (long)_account.accountId,
                             _account.identifier,
                             (long)_account.hasBindPhone];
    UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_jsonString UTF8String]);
    [Tracking setLoginWithAccountID:_account.identifier];
}
-(void) OpenURL:(NSString*) url {
@@ -207,7 +265,7 @@
}
-(void)JPushInit:(NSDictionary*)launchOptions {
    NSLog(@"JPushInit Finished.");
    JPUSHRegisterEntity *_entity = [[JPUSHRegisterEntity alloc] init];
    _entity.types = JPAuthorizationOptionAlert | JPAuthorizationOptionBadge | JPAuthorizationOptionSound;
    if([[UIDevice currentDevice].systemVersion floatValue] > 8.0){
@@ -273,148 +331,97 @@
    [JPUSHService removeNotification:identifier];
}
-(void) ClearAllLocalNotification {
    [JPUSHService removeNotification:nil];
}
-(NSString *) GetIDFA{
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return adId;
}
-(NSString *) GetUserAgent{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    return userAgent;
}
-(NSString*) GetIPAddress {
    NSError* _error;
    NSURL* _url = [NSURL URLWithString:@"http://center.secondworld.net.cn:53004/ad/getip"];
    NSString* _ip = [NSString stringWithContentsOfURL:_url encoding:NSUTF8StringEncoding error:&_error];
    return _ip;
}
-(NSString*) GetUniqueID {
-(void)HandleUnityMessage:(NSString *)json {
    
    NSString* _uniqueID = [[NSUserDefaults standardUserDefaults] objectForKey:@"tsw_unique_id"];
    if(_uniqueID != NULL && [_uniqueID length] > 0)
    {
        NSString *_content = [NSString stringWithFormat:@"{\"code\":%d,\"uniqueID\":\"%@\"}",2013,_uniqueID];
        UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_content UTF8String]);
        return _uniqueID;
    }
    //获取IDFA
    NSString *IDFA = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //判断IDFA是否为空
    BOOL isEmpty = [[IDFA stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByReplacingOccurrencesOfString:@"0" withString:@""].length;
    if (isEmpty) {
        //不为空,将IDFA作为唯一标识
        _uniqueID = IDFA;
    }
    else {
        //为空,获取UUID作为唯一标识
        _uniqueID = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    }
    NSString *_content = [NSString stringWithFormat:@"{\"code\":%d,\"uniqueID\":%@}",2013,_uniqueID];
    UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_content UTF8String]);
    //保存唯一设备标识,如已存在则不进行任何处理
    [[NSUserDefaults standardUserDefaults] setObject:_uniqueID forKey:@"tsw_unique_id"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //返回唯一标识
    return _uniqueID;
}
-(void) GetDeviceInfo {
    NSString* _uniqueID = [[NSUserDefaults standardUserDefaults] objectForKey:@"tsw_unique_id"];
    if(_uniqueID == NULL || [_uniqueID length] <= 0)
    {
        //获取IDFA
        NSString *IDFA = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        //判断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];
    }
    NSString *_jsonString = [NSString stringWithFormat:@"{\"code\":%d,\"userAgent\":\"%@\",\"ip\":\"%@\",\"imei\":\"%@\"}",
                             4100,
                             [self GetUserAgent],
                             [self GetIPAddress],
                             _uniqueID];
    UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_jsonString UTF8String]);
}
-(void)MessageHandler:(NSString *)json {
    NSLog(@"The2thWorldSDK => IOSMessageHandle: (msg = %@)", json);
    NSLog(@"收到Unity发来的消息 => %@", json);
    
    NSData *_jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *_dict = [self APNativeJSONObject:_jsonData];
    
    switch([[_dict objectForKey:@"code"] intValue]){
        case 3100:
        case U2S_Init:
            [self Init];
            break;
        case U2S_CopyContent:
            [UIPasteboard generalPasteboard].string = _dict[@"content"];
            break;
        case U2S_FreePlatformInit:
            [self FreeSDKInit];
            break;
        case 2010:
            [self MakeKeyAndVisible];
        case U2S_MakeKeyAndVisible:
        {
            UIWindow * _window = [[UIApplication sharedApplication].delegate window];
            if (_window != nil && _window.rootViewController != nil) {
                [_window makeKeyAndVisible];
            }
        }
            break;
        case 2011:
        case U2S_OpenWebView:
            [self OpenURL:_dict[@"url"]];
            break;
        case CODE_SDK_FREEPLATFORM_LOGIN:
        case U2S_FreePlatformLogin:
            [FreeSDK presentLoginDialog:nil];
            break;
        case CODE_SDK_FREEPLATFORM_LOGOUT:
        case U2S_FreePlatformLogout:
        {
            if([YLAccount sharedInstance].loggedIn){
                [FreeSDK logout];
            }
            [FreeSDK presentLoginDialog:nil];
            NSString *_content = [NSString stringWithFormat:@"{\"code\":%d}",CODE_SDK_FREEPLATFORM_LOGOUT_OK];
            UnitySendMessage("SDKUtility", "Recv_SDK_Callback",[_content UTF8String]);
            NSDictionary *_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:S2U_FreePlatformLogoutOk], @"code", nil];
            [self SendMessageToUnity:_dict];
            break;
        }
        case CODE_SDK_FREEPLATFORM_PAY:
        case U2S_FreePlatformPay:
        {
            YLOrder *_order = [[YLOrder new] init];
            _order.identifier = [_dict objectForKey:@"identifier"];
            _order.title = [_dict objectForKey:@"title"];
            _order.cpInfo = [_dict objectForKey:@"cpInfo"];
            _order.cpOrderId = [_dict objectForKey:@"cpOrderId"];
            _order.total = [[_dict objectForKey:@"total"] floatValue];
            _order.cpOrderId = [_dict objectForKey:@"orderId"];
            _order.total = [[_dict objectForKey:@"mount"] floatValue];
            [FreeSDK pay:_order];
        }
            break;
        case CODE_SDK_GET_BATTERY_STATE:
            //[self GetBatteryState];
        case U2S_PayFinished:
        {
            [Tracking setRyzf:[_dict objectForKey:@"orderID"]
                     ryzfType:@"freesdk"
                       hbType:[_dict objectForKey:@"moneyType"]
                     hbAmount:[[_dict objectForKey:@"money"] floatValue]];
            [TTTracker purchaseEventWithContentType:@""
                                        contentName:@""
                                          contentID:@""
                                      contentNumber:1
                                     paymentChannel:@"freesdk"
                                           currency:[_dict objectForKey:@"moneyType"]
                                    currency_amount:[[_dict objectForKey:@"money"] intValue]
                                          isSuccess:YES];
        }
            break;
        case CODE_SDK_GET_BATTERY_LEVEL:
            //[self GetBatteryLevel];
        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 CODE_SDK_GETUI_REMOVE_ALLMSG:
            [self ClearAllLocalNotification];
        case U2S_BatteryListenStop:
            break;
        case CODE_SDK_GETUI_REMOVE_MSG:
        case U2S_JPushRemoveLocalMessage:
            [self RemoveLocalNotificationWithIdentifierKey:_dict[@"id"]];
            break;
        case CODE_SDK_GETUI_LOCALMSG_DATETIME:
        case U2S_JPushAddLocalMessage:
        {
            JPushNotificationContent *_content = [[JPushNotificationContent alloc] init];
            if (_dict[@"title"]) {
@@ -514,7 +521,7 @@
extern "C" int native_opus_decode(unsigned char *opus, int len, short *pcm)
{
    int err = 0;
    opus_int32 skip = 0;
    //opus_int32 skip = 0;
    
    OpusDecoder *dec = opus_decoder_create(s_frequency, CHANNEL_NUM, &err);
    if (err != OPUS_OK) {