XenonSDK.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. //
  2. // XenonSDK.m
  3. // XenonSDK
  4. //
  5. // Created by SAGESSE on 2019/3/11.
  6. // Copyright © 2019 SAGESSE. All rights reserved.
  7. //
  8. #import "XenonSDK.h"
  9. #import <Security/Security.h>
  10. #import <sys/utsname.h>
  11. #if SDK_HAS_IDFA
  12. #import <AdSupport/AdSupport.h>
  13. #endif
  14. #import "BubbleView.h"
  15. #import "RootViewController.h"
  16. #import "NoticeViewController.h"
  17. #import "UserBindPhoneViewController.h"
  18. #import "UserLoginFastViewController.h"
  19. #import "UserLoginPhoneViewController.h"
  20. #import "UserCenterViewController.h"
  21. #import "XSUtils.h"
  22. #import <objc/message.h>
  23. @interface XenonSDK ()
  24. @end
  25. ///
  26. /// Game SDK
  27. ///
  28. @implementation XenonSDK
  29. @synthesize user = _user;
  30. @synthesize token = _token;
  31. ///
  32. /// A sington instance of SDK.
  33. ///
  34. + (instancetype)sharedSDK {
  35. static id sharedSDK = nil;
  36. static dispatch_once_t onceToken;
  37. dispatch_once(&onceToken, ^{
  38. sharedSDK = XenonSDK.new;
  39. if (XSNetwork.baseURL == nil) {
  40. XSNetwork.baseURL = @"https://app.funcheergame.com";
  41. }
  42. });
  43. return sharedSDK;
  44. }
  45. ///
  46. /// Init the sdk with application code.
  47. /// \param parameter The parameter provided by the platform.
  48. ///
  49. /// \param complete This closure called when init complete.
  50. ///
  51. - (void)initWithParameter:(NSString*)parameter complete:(void (^)(NSError* error))complete {
  52. // If init is complete, ignore it this call.
  53. if (self.configuration != nil) {
  54. if (complete != nil) {
  55. complete(nil); // sdk is ready.
  56. }
  57. return;
  58. }
  59. // Parse pre-configuration for parameter.
  60. NSArray* configs = [parameter componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"|&"]];
  61. if (configs.count != 4) {
  62. if (complete != nil) {
  63. complete([XSNetwork errorWithCode:-1 message:@"参数错误"]); // error -1
  64. }
  65. return ;
  66. }
  67. // Update pre-configuration for parameter.
  68. self.appId = configs[0];
  69. self.channelId = configs[1];
  70. self.adId = configs[2];
  71. self.adFlag = configs[3];
  72. // Update system configration for server.
  73. [XSNetwork configureWithIdentifier:self.adId flags:self.adFlag complete:^(XSConfiguration* object, NSError *error) {
  74. // If an error occurs, directly callback cp.
  75. if (error != nil) {
  76. if (complete != nil) {
  77. complete(error);
  78. }
  79. return;
  80. }
  81. // An unknown error.
  82. if (object.closeState != 0) {
  83. // Display an system notice.
  84. id qq = self.configuration.fixLinkQQ ?: @"";
  85. id tel = self.configuration.fixLinkTel ?: @"";
  86. // Set the update title & contents.
  87. id contents = [NSString stringWithFormat:@"\n亲爱的玩家您好, 由于服务器紧急维护, 目前游戏暂时无法进入, 给您带来的不便我们深表歉意!\n如果您还有其他问题请与我们联系!\n\n客服QQ: %@\n客服电话: %@", qq, tel];
  88. UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"系统公告" message:contents preferredStyle:UIAlertControllerStyleAlert];
  89. [alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:nil]];
  90. self.rootViewController = alert;
  91. complete([XSNetwork errorWithCode:-8 message:nil]);
  92. return;
  93. }
  94. // Setup sdk with server configuration.
  95. self.configuration = object;
  96. // Get third-party platform parameters.
  97. if (self.configuration.thirdPartyPrams.length != 0) {
  98. NSDictionary* thirdPartyPrams = [NSJSONSerialization JSONObjectWithData:[self.configuration.thirdPartyPrams dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
  99. // If the tracker is turned on, create the object.
  100. int mask = 0;
  101. NSString* dps = thirdPartyPrams[@"dp"];
  102. if (dps.length != 0) {
  103. sscanf(dps.UTF8String, "%x", &mask);
  104. if (mask != 0) {
  105. XSTracker.shared = [XSTracker new];
  106. XSTracker.shared.mask = mask;
  107. [XSNetwork trigger:20];
  108. }
  109. }
  110. // In the initialization.
  111. [XSTracker.shared trace:0x010000 parameters:[NSString stringWithFormat:@"%@", NSProcessInfo.processInfo.environment]];
  112. // If an advertisement parameter is specified, try to parse advertising parameter.
  113. NSString* adPrams = self.configuration.adPrams;
  114. if (adPrams.length != 0) {
  115. // Parse advertising parameter.
  116. [[adPrams componentsSeparatedByString:@"&"] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  117. // Value must be `key=value`
  118. NSArray* tmp = [obj componentsSeparatedByString:@"="];
  119. if (tmp.count != 2) {
  120. return;
  121. }
  122. if ([tmp[0] isEqualToString:@"td_app_id"]) {
  123. self.configuration.tdAppId = tmp[1];
  124. }
  125. if ([tmp[0] isEqualToString:@"td_game_id"]) {
  126. self.configuration.tdGameId = tmp[1];
  127. }
  128. }];
  129. // If td game id is not provided, the TD sdk is not initialized.
  130. if (self.configuration.tdAppId.length != 0 && self.configuration.tdGameId.length != 0) {
  131. // Init for data analzer server.
  132. XSCollector.shared = [[XSCollector alloc] initWithAppId:self.configuration.tdAppId gameId:self.configuration.tdGameId];
  133. }
  134. }
  135. }
  136. [self sdk_checkVersion:^{
  137. [self sdk_checkNote:^{
  138. // Check workflow ended.
  139. [XSTracker.shared trace:0x010001];
  140. // Init sdk complete.
  141. if (complete != nil)
  142. complete(nil);
  143. // init workflow ended.
  144. [XSTracker.shared trace:0x010002];
  145. }];
  146. }];
  147. }];
  148. }
  149. ///
  150. /// Login the sdk.
  151. /// \param complete This closure called when login complete.
  152. ///
  153. - (void)loginWithComplete:(void (^)(id user, NSError* error))complete {
  154. // If init is complete, ignore it this call.
  155. if (self.configuration == nil) {
  156. if (complete != nil)
  157. complete(nil, [XSNetwork errorWithCode:-1 message:@"请先初始化"]); // error -1
  158. return;
  159. }
  160. [XSTracker.shared trace:0x010010];
  161. // Unified operation after successful login.
  162. void (^loginedCallback)(void) = ^{
  163. // Build return data.
  164. id user = nil;
  165. if (self.user != nil) {
  166. user = @{
  167. @"uid": self.user.uid,
  168. @"token": self.user.token,
  169. @"userName": self.user.userName ?: @"",
  170. @"phone": self.user.phone ?: @""
  171. };
  172. // According to air bubbles.
  173. if (!self.configuration.isFloatDisable) {
  174. UIWindow* window = UIApplication.sharedApplication.delegate.window ?: UIApplication.sharedApplication.keyWindow;
  175. BubbleView* view = [[BubbleView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
  176. [view.contentView addTarget:self action:@selector(center) forControlEvents:UIControlEventTouchUpInside];
  177. [window addSubview:view];
  178. // It's shown in the first one.
  179. UIView* xmp = [window viewWithTag:-1];
  180. if (xmp != nil) {
  181. [window bringSubviewToFront:xmp];
  182. }
  183. [self.bubbleView removeFromSuperview];
  184. self.bubbleView = view;
  185. }
  186. [XSTracker.shared trace:0x010013];
  187. }
  188. [XSTracker.shared trace:0x010011];
  189. if (complete) {
  190. complete(user, nil);
  191. }
  192. [XSTracker.shared trace:0x010012];
  193. };
  194. // Try automatically login if needed.
  195. if (self.user != nil) {
  196. [XSNetwork showHudLoading];
  197. [XSNetwork authWithUser:self.user.uid complete:^(XSUser* user, NSError *error) {
  198. // If the login fails, clear the user information and login again.
  199. if (user.token.length == 0 || error != nil) {
  200. [XSNetwork showHudFailure:@"登录时效期已过,请重新登录"];
  201. self.user = nil;
  202. [self loginWithComplete:complete];
  203. return;
  204. }
  205. // Update user info.
  206. XSUser* duser = self.user;
  207. duser.token = user.token;
  208. duser.isRegister = false;
  209. self.user = duser;
  210. // Login successful, display HUD.
  211. [XSNetwork showPrompt:duser.name];
  212. // Check if the user is already connected to the phone.
  213. [self sdk_checkPhone:^{
  214. loginedCallback();
  215. }];
  216. }];
  217. [XSTracker.shared trace:0x010014];
  218. return;
  219. }
  220. // Setup login callback.
  221. __weak __typeof(self) ws = self;
  222. self.sdk_loginCallback = ^(XSUser* user) {
  223. [ws setUser:user];
  224. [ws.rootViewController dismissViewControllerAnimated:YES completion:nil];
  225. // Login successful, display HUD.
  226. [XSNetwork showPrompt:user.name];
  227. // Check if the user is already connected to the phone.
  228. [ws sdk_checkPhone:^{
  229. loginedCallback();
  230. }];
  231. };
  232. // The last time was to log out, so the quick login list is displayed.
  233. if (XSUser.history.count != 0) {
  234. self.rootViewController = [[RootViewController alloc] initWithRootViewController:UserLoginFastViewController.new];
  235. return;
  236. }
  237. // To account login
  238. self.rootViewController = [[RootViewController alloc] initWithRootViewController:UserLoginPhoneViewController.new];
  239. }
  240. ///
  241. /// Logout the sdk.
  242. /// \param complete This closure called when logout complete.
  243. ///
  244. - (void)logoutWithComplete:(void (^)(void))complete {
  245. // If init is complete, ignore it this call.
  246. if (self.configuration == nil) {
  247. if (complete != nil)
  248. complete();
  249. return;
  250. }
  251. self.user = nil;
  252. [self.bubbleView removeFromSuperview];
  253. self.bubbleView = nil;
  254. if (complete != nil)
  255. complete();
  256. [XSTracker.shared trace:0x010020];
  257. }
  258. ///
  259. /// Logout the game and sdk.
  260. /// \param handler This closure called when user logout in web view.
  261. /// \note Warning this handler will retain in until next call this method.
  262. ///
  263. - (void)logoutWhenNotification:(void (^)(void))handler {
  264. self.sdk_logoutCallback = ^(id user) {
  265. if (handler != nil)
  266. handler();
  267. [XSTracker.shared trace:0x010020];
  268. };
  269. }
  270. ///
  271. /// Buy a product.
  272. /// \param parameters Payment request parameters.
  273. /// \param complete Payment result of the callback, if the apple payment is completed before the callback, other payments will be the official launch of the callback
  274. ///
  275. - (void)buy:(NSDictionary*)parameters complete:(void (^)(id order, NSError* error))complete {
  276. // Check paramrters.
  277. if (self.configuration == nil || self.user == nil) {
  278. if (complete != nil) {
  279. complete(nil, [XSNetwork errorWithCode:-1 message:@"请先登录"]); // error -1
  280. return ;
  281. }
  282. }
  283. [XSTracker.shared trace:0x010030];
  284. [XSNetwork showHudLoading];
  285. [XSNetwork routeWithComplete:^(id object, NSError *error) {
  286. if (error != nil) {
  287. [XSNetwork showHudFailure:error];
  288. if (complete != nil) {
  289. complete(nil, error);
  290. }
  291. return;
  292. }
  293. // Get parmeters.
  294. XSUser* user = self.user;
  295. NSString* path = object[fqsd(@"PREAACs/NCYsJjQuLRkA")];
  296. #if SDK_HAS_H5_PAYMENT
  297. // Generate h5 payment parameters.
  298. if (path.length != 0) {
  299. [XSNetwork hideHud];
  300. [XSTracker.shared trace:0x010031];
  301. id payments = @{
  302. @"cpBillNo": parameters[@"orderId"] ?: @"",
  303. @"orderAmount": parameters[@"amount"] ?: @"",
  304. @"subject": parameters[@"productName"] ?: @"",
  305. @"roleName": parameters[@"roleName"] ?: @"",
  306. @"serverId": parameters[@"serverId"] ?: @"",
  307. @"extraInfo": parameters[@"extraInfo"] ?: @"",
  308. @"phone": @"",
  309. @"isTest": @"1",
  310. @"orderPlatform": @"0",
  311. @"orderType": @"1",
  312. @"remark": @"0",
  313. @"isApp": @"0",
  314. @"uid": user.uid,
  315. @"userName": user.userName ?: @""
  316. };
  317. NSURLComponents* components = [NSURLComponents componentsWithString:path];
  318. NSDictionary* json = [XSNetwork bodyWithParameters:payments];
  319. NSString* str = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:json options:0 error:nil] encoding:NSUTF8StringEncoding];
  320. components.queryItems = @[[NSURLQueryItem queryItemWithName:@"jsonData" value:str],
  321. [NSURLQueryItem queryItemWithName:@"v" value:@"1"]];
  322. if (components.URL == nil) {
  323. if (complete != nil) {
  324. complete(nil, [XSNetwork errorWithCode:-1 message:@"后台参数错误"]);
  325. }
  326. return;
  327. }
  328. UserCenterViewController* rootViewController = UserCenterViewController.new;
  329. rootViewController.custom = components.URL.absoluteString;
  330. rootViewController.otherView = self.bubbleView;
  331. rootViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
  332. self.rootViewController = rootViewController;
  333. // Cannot get the callback state.
  334. rootViewController.callback = ^{
  335. if (complete != nil) {
  336. complete(nil, nil);
  337. }
  338. };
  339. return;
  340. }
  341. #endif
  342. #if SDK_HAS_IAP_PAYMENT
  343. // Generate iap payment parameters.
  344. id payments = @{
  345. @"productCode": parameters[@"productCode"] ?: @"",
  346. @"isCoin": @"0",
  347. @"orderPlatform": @"0",
  348. @"orderType": @"1",
  349. @"orderAmount": parameters[@"amount"] ?: @"",
  350. @"isTest": @"0",
  351. @"subject": parameters[@"productName"] ?: @"",
  352. @"roleName": parameters[@"roleName"] ?: @"",
  353. @"cpBillNo": parameters[@"orderId"] ?: @"",
  354. @"remark": @"0",
  355. @"serverId": parameters[@"serverId"] ?: @"",
  356. @"extraInfo": parameters[@"extraInfo"] ?: @"",
  357. @"uid": user.uid,
  358. @"userName": user.userName ?: @""
  359. };
  360. [XSTracker.shared trace:0x010032];
  361. [XSNetwork payWithParameters:payments complete:^(id object, NSError *error) {
  362. if (error != nil) {
  363. [XSNetwork showHudFailure:error];
  364. if (complete != nil) {
  365. complete(nil, error);
  366. }
  367. return;
  368. }
  369. [XSTracker.shared trace:0x010034];
  370. [XSNetwork showHudSuccess:@"支付成功"];
  371. if (complete != nil)
  372. complete(payments, nil);
  373. }];
  374. #endif
  375. }];
  376. }
  377. ///
  378. /// User Center.
  379. ///
  380. - (void)center {
  381. if (self.configuration == nil || self.user == nil) {
  382. return;
  383. }
  384. [XSTracker.shared trace:0x010040];
  385. UserCenterViewController* rootViewController = UserCenterViewController.new;
  386. rootViewController.otherView = self.bubbleView;
  387. rootViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
  388. self.rootViewController = rootViewController;
  389. }
  390. /// Report role info.
  391. /// \param roleName This role name.
  392. ///
  393. /// \param level This role current level.
  394. ///
  395. /// \param serverId This role current server.
  396. ///
  397. - (void)reportWithRoleName:(NSString*)roleName level:(NSInteger)level serverId:(NSString*)serverId {
  398. if (self.configuration == nil || self.user == nil) {
  399. return;
  400. }
  401. [XSNetwork reportWithUser:self.user.userName Name:roleName level:level server:serverId];
  402. [XSCollector.shared reportWithAccount:self.user.uid name:roleName level:level server:serverId];
  403. }
  404. // MARK: -
  405. - (void)sdk_checkVersion:(void(^)(void))complete {
  406. // If no configuration file is provided, initialization failed.
  407. if (self.configuration == nil) {
  408. complete();
  409. return;
  410. }
  411. // If update cheker is not enabled, ignore it.
  412. NSURL* url = [NSURL URLWithString:self.configuration.updateUrl];
  413. if (url == nil || self.configuration.updateState == 0) {
  414. complete();
  415. return;
  416. }
  417. // If the prompt is too frequent, wait.
  418. // 1 is normal update.
  419. if (self.configuration.updateState == 1 && !([XSDataCenter doubleForKey:@"verion-later"] < NSDate.new.timeIntervalSince1970)) {
  420. complete();
  421. return;
  422. }
  423. NoticeViewController* viewController = NoticeViewController.new;
  424. // Set the update title & contents.
  425. viewController.title = @"发现新版本";
  426. viewController.contents = [NSString stringWithFormat:@"亲爱的玩家您好,我们发布了新的版本, 更新到新版本可体验更多新奇有趣的玩法!\n\n最新版本: %@\n当前版本: %@\n\n\n", self.configuration.updateVersion, self.shortVersion];
  427. // Set the confirm closure.
  428. [viewController addActionWithName:@"立即升级" handler:^{
  429. // -[UIApplication openURL:]
  430. ((void(*)(id,SEL,id))objc_msgSend)(UIApplication.sharedApplication, NSSelectorFromString(fqsd(@"p2cAAMrAyrKwq5rIAA==")), url);
  431. }];
  432. // Set the cancel closure.
  433. if (self.configuration.updateState == 1) {
  434. __weak __typeof(self) ws = self;
  435. [viewController addActionWithName:@"稍后再说" handler:^{
  436. // Again 24 hours later.
  437. [XSDataCenter setDouble:[NSDate dateWithTimeIntervalSinceNow:24*60*60].timeIntervalSince1970 forKey:@"verion-later"];
  438. if (ws.rootViewController == nil) {
  439. complete();
  440. return;
  441. }
  442. // Automatic hidden controller.
  443. [ws.rootViewController dismissViewControllerAnimated:YES completion:complete];
  444. }];
  445. }
  446. // Show view contorller in key window.
  447. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  448. self.rootViewController = [[RootViewController alloc] initWithRootViewController:viewController];
  449. });
  450. }
  451. - (void)sdk_checkNote:(void(^)(void))complete {
  452. // If no configuration file is provided, initialization failed.
  453. NSURL* url = [NSURL URLWithString:self.configuration.closeUrl];
  454. if (url == nil || self.configuration.linkQq == 0) {
  455. complete();
  456. return ;
  457. }
  458. // If the announcement is displayed, it is no longer displayed.
  459. if (self.configuration.linkQq != 2 && [[XSDataCenter stringForKey:@"notice-later"] isEqualToString:url.absoluteString]) {
  460. complete();
  461. return;
  462. }
  463. NoticeViewController* viewController = NoticeViewController.new;
  464. // Set the update title & contents.
  465. viewController.title = @"系统公告";
  466. viewController.contents = url;
  467. // Set the confirm closure.
  468. __weak __typeof(self) ws = self;
  469. [viewController addActionWithName:@"我知道了" handler:^{
  470. // Never again.
  471. [XSDataCenter setString:url.absoluteString forKey:@"notice-later"];
  472. if (ws.rootViewController == nil) {
  473. complete();
  474. return;
  475. }
  476. // Automatic hidden controller.
  477. [ws.rootViewController dismissViewControllerAnimated:YES completion:complete];
  478. }];
  479. // Show view contorller in key window.
  480. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  481. self.rootViewController = [[RootViewController alloc] initWithRootViewController:viewController];
  482. });
  483. }
  484. - (void)sdk_checkPhone:(void(^)(void))complete {
  485. // Check if the phone character exists.
  486. if (self.user.isRegister || self.user.phone.length != 0 || self.configuration.serverStatus == 1) {
  487. complete();
  488. return;
  489. }
  490. // If the prompt is too frequent, wait.
  491. id key = [NSString stringWithFormat:@"%@-bind-later", self.user.uid];
  492. if ([XSDataCenter doubleForKey:key] > NSDate.new.timeIntervalSince1970) {
  493. complete();
  494. return;
  495. }
  496. UserBindPhoneViewController* bindViewController = UserBindPhoneViewController.new;
  497. RootViewController* rooViewController = [[RootViewController alloc] initWithRootViewController:bindViewController];
  498. UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您的帐号存在风险, 为了您的帐号安全建议您绑定手机号。" preferredStyle:UIAlertControllerStyleAlert];
  499. // Add confirm action.
  500. [alert addAction:[UIAlertAction actionWithTitle:@"绑定手机" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  501. bindViewController.callback = complete;
  502. self.rootViewController = rooViewController;
  503. }]];
  504. // Add cancel action.
  505. [alert addAction:[UIAlertAction actionWithTitle:@"稍后提醒" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  506. // Again 24 hours later.
  507. [XSDataCenter setDouble:[NSDate dateWithTimeIntervalSinceNow:24*60*60].timeIntervalSince1970 forKey:key];
  508. // Continue.
  509. complete();
  510. }]];
  511. (void)rooViewController.view; // preload;
  512. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  513. self.rootViewController = alert;
  514. });
  515. // Hide all hud if needed.
  516. [XSNetwork hideHud];
  517. }
  518. // MARK: -
  519. - (void)setUser:(XSUser *)user {
  520. _user = user;
  521. _token = user.token;
  522. // Cache.
  523. [XSDataCenter setValue:user forKey:@"User.current"];
  524. if (user == nil) {
  525. return;
  526. }
  527. // Make a new login history.
  528. NSMutableSet* ids = [NSMutableSet set];
  529. NSMutableArray* history = [NSMutableArray array];
  530. user.lastTime = NSDate.new.timeIntervalSince1970;
  531. [ids addObject:user.uid];
  532. [history addObject:user];
  533. for (XSUser* tmp in XSUser.history) {
  534. if (![ids containsObject:tmp.uid]) {
  535. [ids addObject:tmp.uid];
  536. [history addObject:tmp];
  537. }
  538. }
  539. XSUser.history = history;
  540. }
  541. - (XSUser*)user {
  542. if (_user != nil) {
  543. return _user;
  544. }
  545. static dispatch_once_t onceToken;
  546. dispatch_once(&onceToken, ^{
  547. self->_user = [XSDataCenter valueForKey:@"User.current"];
  548. self->_token = self->_user.token;
  549. });
  550. return _user;
  551. }
  552. - (void)setRootViewController:(UIViewController *)rootViewController {
  553. _rootViewController = rootViewController;
  554. if (rootViewController == nil) {
  555. return;
  556. }
  557. [UIApplication.sharedApplication.keyWindow.rootViewController presentViewController:rootViewController
  558. animated:YES
  559. completion:nil];
  560. }
  561. /// Permanent preservation of data.
  562. - (void)setPermanentValue:(NSString*)value forKey:(NSString*)key {
  563. // Set value to user defautls.
  564. [XSDataCenter setString:value forKey:key];
  565. // Configure the search setting.
  566. id setting = @{
  567. // Configure the keychain key type.
  568. CFBridgingRelease(kSecClass): CFBridgingRelease(kSecClassGenericPassword),
  569. CFBridgingRelease(kSecAttrAccount): key
  570. }.mutableCopy;
  571. // Delete old item before add new item
  572. SecItemDelete(CFBridgingRetain(setting));
  573. // Add new object to search dictionary.
  574. [setting setObject:[value dataUsingEncoding:NSUTF8StringEncoding] forKey:CFBridgingRelease(kSecValueData)];
  575. // Add item to keychain with the search dictionary
  576. SecItemAdd(CFBridgingRetain(setting), nil);
  577. }
  578. /// Read data for permanent preservationed.
  579. - (id)permanentValueForKey:(NSString*)key {
  580. // Read data from user defatuls.
  581. NSString* udid = [XSDataCenter stringForKey:key];
  582. if (udid.length != 0) {
  583. return udid;
  584. }
  585. // Configure the search setting.
  586. id setting = @{
  587. // Configure the keychain key type.
  588. CFBridgingRelease(kSecClass): CFBridgingRelease(kSecClassGenericPassword),
  589. // The class name of the SDK is dynamic.
  590. CFBridgingRelease(kSecAttrService): NSStringFromClass(self.class),
  591. CFBridgingRelease(kSecAttrAccount): key,
  592. // Gets result data of data.
  593. CFBridgingRelease(kSecReturnData): CFBridgingRelease(kCFBooleanTrue)
  594. };
  595. // Start query the keychain query.
  596. CFTypeRef result = nil;
  597. if (SecItemCopyMatching(CFBridgingRetain(setting), &result) == noErr) {
  598. return nil;
  599. }
  600. // Convert data to a string
  601. NSString* value = [[NSString alloc] initWithData:CFBridgingRelease(result) encoding:NSUTF8StringEncoding];
  602. if (value.length == 0) {
  603. return nil;
  604. }
  605. // Set value to user defautls, reduce Keychain access count.
  606. [XSDataCenter setString:value forKey:key];
  607. return value;
  608. }
  609. - (NSString*)advertisingIdentifier {
  610. // Read the data from keychain.
  611. NSString* advertisingIdentifier = [self permanentValueForKey:@"udid"];
  612. if (advertisingIdentifier.length != 0) {
  613. return advertisingIdentifier;
  614. }
  615. #if SDK_HAS_IDFA
  616. // Try to obtain idfa.
  617. ASIdentifierManager* advertisingManager = ASIdentifierManager.sharedManager;
  618. advertisingIdentifier = advertisingManager.advertisingIdentifier.UUIDString;
  619. if (!advertisingManager.isAdvertisingTrackingEnabled) {
  620. advertisingIdentifier = [NSString stringWithFormat:@"#%@", NSUUID.new.UUIDString];
  621. }
  622. #else
  623. // Generate an id to replace idfa.
  624. advertisingIdentifier = [NSString stringWithFormat:@"#%@", NSUUID.new.UUIDString];
  625. #endif
  626. // Save to keychain to prevent updates.
  627. [self setPermanentValue:advertisingIdentifier forKey:@"udid"];
  628. return advertisingIdentifier;
  629. }
  630. - (NSString*)advertisingVendor {
  631. // This parameter has been deprecated and must be empty string.
  632. return @"";
  633. }
  634. - (NSBundle*)bundle {
  635. return [NSBundle bundleForClass:self.class];
  636. }
  637. - (NSString*)model {
  638. struct utsname sinfo;
  639. uname(&sinfo);
  640. return [NSString stringWithUTF8String: sinfo.machine];
  641. }
  642. /// The sdk verions.
  643. - (NSString*)version {
  644. return self.bundle.infoDictionary[@"CFBundleShortVersionString"] ?: @"1.0";
  645. }
  646. /// The game verions.
  647. - (NSString*)shortVersion {
  648. return NSBundle.mainBundle.infoDictionary[@"CFBundleShortVersionString"] ?: @"1.0";
  649. }
  650. //横幅广告
  651. -(void)adBanner:(NSString *)adId {
  652. [[FqGameAd fqGameAD] showBanner:adId];
  653. }
  654. //关闭横幅广告
  655. - (void)closeBanner:(NSString *)adId {
  656. [[FqGameAd fqGameAD] closeBanner:adId];
  657. }
  658. //显示插页广告
  659. -(void)adInner:(NSString *)adId complete:(void (^)(int))complete {
  660. [[FqGameAd fqGameAD] showInner:adId callback:^(int intValue) {
  661. complete(intValue);
  662. }];
  663. }
  664. //视频激励广告
  665. -(void)adVideo:(NSString *)adId complete:(void (^)(int))complete {
  666. [[FqGameAd fqGameAD] showVideo:adId callback:^(int intValue) {
  667. complete(intValue);
  668. }];
  669. }
  670. //广告是否准备好
  671. /// @parm callback YES:可用, NO:不可用
  672. -(void)isAdReady:(NSString *)adName callback:(void(^)(BOOL))callback {
  673. BOOL ready = [[FqGameAd fqGameAD] isAdReady:adName];
  674. callback(ready);
  675. }
  676. //打开广告
  677. -(void)openAd:(NSString *)adName {
  678. [[FqGameAd fqGameAD] openAd:adName];
  679. }
  680. //打开原生广告
  681. -(void)adNative:(NSString *)adId x:(int)x y:(int)y w:(int)width h:(int)hight {
  682. [[FqGameAd fqGameAD] showAdNative:adId x:x y:y w:width h:hight];
  683. }
  684. //关闭原生广告
  685. -(void)closeNative {
  686. [[FqGameAd fqGameAD] closeNative];
  687. }
  688. //关闭原生广告(通过adId)
  689. -(void)closeNative:(NSString *)adName {
  690. [[FqGameAd fqGameAD] closeNative:adName];
  691. }
  692. ///生命周期启动入口
  693. /// @param application application对象
  694. -(void)applicationDidFinishLaunching:(UIApplication *)application {
  695. //...
  696. }
  697. /// 游戏进入后台
  698. -(void)applicationDidEnterBackground{
  699. //...
  700. }
  701. /// 游戏进入到前台
  702. -(void)applicationWillEnterForeground{
  703. //...
  704. }
  705. /// 游戏开始活跃运行
  706. -(void)applicationDidBecomeActive{
  707. //...
  708. }
  709. ///手机震动
  710. -(void)iphoneVibrate {
  711. //手机--设置--声音--响铃模式震动(打开),不然无效.
  712. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
  713. }
  714. //跳转appstore评论
  715. -(void)skipToAppsotreWithID:(NSString *)appleId {
  716. NSString *urlStr = [NSString stringWithFormat:@"https://itunes.apple.com/us/app/itunes-u/id%@?action=write-review&mt=8",
  717. appleId];
  718. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
  719. }
  720. ///自动登录
  721. -(void)autoLogin {
  722. XSUser* user = [XSDataCenter valueForKey:@"User.current"];
  723. if (user.uid.length == 0) {
  724. return;
  725. }
  726. // Try authorization login.
  727. XenonSDK.sharedSDK.token = user.token;
  728. [XSNetwork authWithUser:user.uid complete:^(XSUser* object, NSError *error) {
  729. // Check for general errors.
  730. if (error != nil && ![error.domain isEqual:@"XSNetwork"]) {
  731. [XSNetwork showHudFailure:error];
  732. return;
  733. }
  734. // Login successful.
  735. if (user.token.length != 0 && error == nil) {
  736. // Update user info.
  737. user.token = object.token;
  738. user.isRegister = NO;
  739. XenonSDK.sharedSDK.user = user;
  740. if (XenonSDK.sharedSDK.sdk_loginCallback) {
  741. XenonSDK.sharedSDK.sdk_loginCallback(user);
  742. }
  743. return;
  744. }
  745. [XSNetwork showHudFailure:@"登录时效期已过,请重新登录"];
  746. // Login failed to login page.
  747. UserLoginPhoneViewController* viewController = UserLoginPhoneViewController.new;
  748. [viewController automatic:user.account];
  749. [self.rootViewController.navigationController pushViewController:viewController animated:YES];
  750. }];
  751. }
  752. ///手动登录
  753. -(void)manualLogin {
  754. //XSUser *user = [XSDataCenter valueForKey:@"User.current"];
  755. if (XSUser.history.count != 0) {
  756. self.rootViewController = [[RootViewController alloc] initWithRootViewController:UserLoginFastViewController.new];
  757. return;
  758. }
  759. // To account login
  760. self.rootViewController = [[RootViewController alloc] initWithRootViewController:UserLoginPhoneViewController.new];
  761. }
  762. @end