AppDelegate.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. //
  2. // AppDelegate.m
  3. //
  4. //
  5. // Created by yhw on 2021/12/8.
  6. //
  7. #import "AppDelegate.h"
  8. #import <CoreMotion/CoreMotion.h>
  9. #import "ShearDeviceUDPManager.h"
  10. #import "AudioSessionObject.h"
  11. #import "DDYLanguageTool.h"
  12. #import "PLeakSniffer.h"
  13. #import "connectDeviceManager.h"
  14. #import <Bugly/Bugly.h>
  15. #import <JJException/JJException.h>
  16. #import <WXApi.h>
  17. #import <TencentOpenAPI/QQApiInterface.h>
  18. #import <TencentOpenAPI/TencentOAuth.h>
  19. #import <SDWebImage/SDWebImage.h>
  20. //#import <ZFPlayer/ZFLandscapeRotationManager.h>
  21. #import "ZFLandscapeRotationManager.h"
  22. #import <WebRTC/AMediaStream.h>
  23. #import "pingManager.h"
  24. #import "nasUploadFileManager.h"
  25. @interface AppDelegate ()<JJExceptionHandle,WXApiDelegate>
  26. {
  27. CMMotionManager *cmManager;
  28. NSString * NASFileByBoxServiceByPingok;//内网地址
  29. NSString * NASFileByBoxServiceByPingNot;//外网地址
  30. }
  31. @end
  32. @implementation AppDelegate
  33. + (AppDelegate*)sharedAppDelegate
  34. {
  35. static AppDelegate *appDelegate = nil;
  36. static dispatch_once_t onceToken;
  37. dispatch_once(&onceToken, ^{
  38. if (appDelegate == nil) {
  39. appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  40. }
  41. });
  42. return appDelegate;
  43. }
  44. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  45. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDarkContent];
  46. //帮客户生成秘钥
  47. // NSString *snStr = @"0333933700222450011053";
  48. // NSString *secretkey = [RSATool sha256_8:snStr];
  49. // HLog(@"%@",secretkey);
  50. [AMediaStream globalInitialization];
  51. //保护App,一般常见的问题不会导致闪退,增强App的健壮性,同时会将错误抛出来,根据每个App自身的日志渠道记录
  52. [JJException configExceptionCategory:JJExceptionGuardAll];
  53. [JJException startGuardException];
  54. [JJException registerExceptionHandle:self];
  55. // //Default value:NO no表示异常不退出 YES 表示退出 开发时应该设置为YES
  56. // JJException.exceptionWhenTerminate = YES;
  57. //test code
  58. // NSArray * arr = @[];
  59. // NSString *str = arr[2];
  60. [self setLanguagesFun];
  61. //设置默认值
  62. self.couldPhone_W_PHONE = 720.0;
  63. self.couldPhone_H_PHONE = 1280.0;
  64. // self.couldPhone_W_PHONE = 1080.0;
  65. // self.couldPhone_H_PHONE = 1920.0;
  66. [[UIButton appearance] setExclusiveTouch:YES];
  67. cmManager = [[CMMotionManager alloc] init];
  68. if (cmManager.isAccelerometerAvailable){
  69. HLog(@"\n-------摇一摇可用-----");
  70. }else{
  71. HLog(@"\n-------摇一摇不可用-----");
  72. }
  73. cmManager.accelerometerUpdateInterval = 0.1;
  74. [cmManager startAccelerometerUpdates];
  75. [cmManager startDeviceMotionUpdatesToQueue:[NSOperationQueue new] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
  76. // CMRotationRate rotationRate = motion.rotationRate;
  77. // CGFloat rotationRatex = rotationRate.x;
  78. // CGFloat rotationRatey = rotationRate.y;
  79. // CGFloat rotationRatez = rotationRate.z;
  80. CMAcceleration accrleration = motion.gravity;
  81. CGFloat rotationGravityz = accrleration.z;
  82. //HLog(@"rotationRatey: %f",rotationRatey)
  83. //HLog(@"rotationGravityz: %f",rotationGravityz)
  84. //if (rotationRatey > 7){
  85. if (rotationGravityz > 0.85){
  86. BOOL haveOpenMask = [HWDataManager getBoolWithKey:Consn_Fanzhuan_Exit_app_Open];
  87. BOOL isPrivacyMode = ksharedAppDelegate.DeviceThirdIdMod.data.isPrivacyMode;
  88. if (haveOpenMask && isPrivacyMode){
  89. exit(0);/*强制退出app*/
  90. }
  91. }
  92. }];
  93. // [[ShearDeviceUDPManager shareInstance] startShearchDevice];
  94. // [[ShearDeviceUDPManager shareInstance] shearchDeviceLoop];
  95. //启动后台保活
  96. [AudioSessionObject shareManager];
  97. [self MonitorNetworkChangesFun];
  98. #ifdef DEBUG
  99. [[PLeakSniffer sharedInstance] installLeakSniffer];
  100. #else
  101. #endif
  102. [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
  103. [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
  104. [[UIDevice currentDevice] batteryLevel];
  105. // 监听电池电量变化通知
  106. //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
  107. //微信注册
  108. [WXApi registerApp:WXAPPid universalLink:wxuniversalLink];
  109. [TencentOAuth setIsUserAgreedAuthorization:YES];
  110. TencentOAuth *tencentOAuth =[[TencentOAuth alloc] initWithAppId:QQAPPid andUniversalLink:QQUniversalLink andDelegate:self];
  111. [self imageLoadingSettings];
  112. return YES;
  113. }
  114. /// 在这里写支持的旋转方向,为了防止横屏方向,应用启动时候界面变为横屏模式
  115. - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  116. ZFInterfaceOrientationMask orientationMask = [ZFLandscapeRotationManager supportedInterfaceOrientationsForWindow:window];
  117. if (orientationMask != ZFInterfaceOrientationMaskUnknow) {
  118. return (UIInterfaceOrientationMask)orientationMask;
  119. }
  120. HLog(@"处理旋转屏幕:%d",self.supportScreenRotateType)
  121. //显示密码了
  122. if(ksharedAppDelegate.isDidShowPwdType){
  123. return UIInterfaceOrientationMaskPortrait;
  124. }
  125. if(self.supportScreenRotateType){
  126. return UIInterfaceOrientationMaskAllButUpsideDown;
  127. }
  128. if(self.isPlayerScreenLandscapeType){
  129. return UIInterfaceOrientationMaskLandscapeRight;
  130. }
  131. return UIInterfaceOrientationMaskPortrait;
  132. }
  133. - (void)applicationWillTerminate:(UIApplication *)application {
  134. //
  135. [AMediaStream globalDeinitialization];
  136. }
  137. #pragma mark - UISceneSession lifecycle
  138. - (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
  139. // Called when a new scene session is being created.
  140. // Use this method to select a configuration to create the new scene with.
  141. return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
  142. }
  143. - (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
  144. // Called when the user discards a scene session.
  145. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  146. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  147. }
  148. - (void)applicationWillEnterForeground:(UIApplication *)application {
  149. // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
  150. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  151. NSString *orderNumber = [HWDataManager getStringWithKey:Const_AirpayOrWXorderNum];
  152. if (orderNumber && ![orderNumber isEqualToString:@""])
  153. {
  154. [[NSNotificationCenter defaultCenter] postNotificationName:NotNameAirpayOrWXorderNum object:orderNumber];
  155. }
  156. });
  157. }
  158. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
  159. return [WXApi handleOpenURL:url delegate:self];
  160. }
  161. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
  162. if (YES == [TencentOAuth CanHandleOpenURL:url])
  163. {
  164. return [TencentOAuth HandleOpenURL:url];
  165. }
  166. return [WXApi handleOpenURL:url delegate:self];
  167. }
  168. - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
  169. {
  170. if([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
  171. NSURL *url = userActivity.webpageURL;
  172. if(url && [TencentOAuth CanHandleUniversalLink:url]) {
  173. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CI UniversalLink" message:url.description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
  174. [alertView show];
  175. //[QQApiInterface handleOpenUniversallink:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
  176. return [TencentOAuth HandleUniversalLink:url];
  177. }
  178. }
  179. return [WXApi handleOpenUniversalLink:userActivity delegate:self];
  180. }
  181. #pragma mark 监听网络变化
  182. -(void)MonitorNetworkChangesFun
  183. {
  184. [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  185. HLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
  186. mainBlock((^{
  187. //[[iToast makeText:[[NSString alloc] initWithFormat:@"Reachability:%@",AFStringFromNetworkReachabilityStatus(status)] ] show];
  188. [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkChangeNotification object:nil];
  189. }));
  190. //网络切换
  191. [self handelNetWorkChangeFunBy:status];
  192. }];
  193. [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  194. }
  195. #pragma mark 处理网络切换情况
  196. - (void)handelNetWorkChangeFunBy:(AFNetworkReachabilityStatus)status
  197. {
  198. if(status == AFNetworkReachabilityStatusReachableViaWiFi){//检测到起切换wifi 重新ping一下
  199. [[pingManager shareManager] startPingDeviceIpFun];
  200. }
  201. else {//非wifi链接
  202. [pingManager shareManager].isPingOk = NO;
  203. }
  204. //是否备份中 处理切换网络环境 用户无感备份切换
  205. if(([nasBackupsManager shareInstance].curPhotosBackupsTaskMod
  206. && [nasBackupsManager shareInstance].curPhotosBackupsTaskMod.curBackupsState == backupsStateUploading)
  207. || [nasBackupsManager shareInstance].isWifiNeedReBackupsType){
  208. //1.先暂停备份
  209. [[nasBackupsManager shareInstance] suspendBackupsFileFun];
  210. //2.重新开启备份
  211. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  212. [[nasBackupsManager shareInstance] reBackupsFileFun];
  213. });
  214. }
  215. //是否上传中 处理切换网络环境 用户无感上传切换
  216. BOOL needToReUploadTaskType = [nasUploadFileManager shareInstance].needToReUploadTaskType;
  217. if(needToReUploadTaskType){//如果网络层先保存 这里为YES
  218. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  219. [[nasUploadFileManager shareInstance] reUploadFileFunByNetWork];
  220. });
  221. }
  222. else{
  223. //有可能是网络变化先收到通知
  224. if([nasUploadFileManager shareInstance].uploadingArr.count > 0){
  225. [[nasUploadFileManager shareInstance] saveUploadingTaskByNetWorkErrorFun];
  226. //因为不知道是网络变化通知快 还是传输快 这里5秒后重新传
  227. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  228. [[nasUploadFileManager shareInstance] reUploadFileFunByNetWork];
  229. });
  230. }
  231. }
  232. //HLog(@"hxd 1111")
  233. //是否下载中 处理切换网络环境 用户无感下载切换
  234. BOOL needToReDownloadTaskType = [nasDownloadFileManager shareInstance].needToReDownloadTaskType;
  235. if(needToReDownloadTaskType){//如果网络层先保存 这里为YES
  236. //HLog(@"hxd 2222")
  237. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  238. [[nasDownloadFileManager shareInstance] reDownloadloadFileFunByNetWork];
  239. });
  240. }
  241. else{
  242. //HLog(@"hxd 3333")
  243. //有可能是网络变化先收到通知
  244. if([nasDownloadFileManager shareInstance].downLoadFileModelDataArr.count > 0){
  245. //HLog(@"hxd 4444")
  246. [[nasDownloadFileManager shareInstance] saveDownloadloadingTaskByNetWorkErrorFun];
  247. //因为不知道是网络变化通知快 还是传输快 这里5秒后重新传
  248. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  249. [[nasDownloadFileManager shareInstance] reDownloadloadFileFunByNetWork];
  250. });
  251. }
  252. }
  253. }
  254. #pragma mark 多国语言相关
  255. -(void)setLanguagesFun{
  256. NSArray *arLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
  257. NSLog(@"arLanguages:%@",arLanguages);
  258. ///获取设备当前地区的代码和APP语言环境
  259. NSString *languageCode = [NSLocale preferredLanguages][0];
  260. // 获取国际通用国家地区代码(应该和手机本身有关)
  261. NSString *countryCode = [NSString stringWithFormat:@"-%@", [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]];
  262. // if (languageCode) {
  263. // languageCode = [languageCode stringByReplacingOccurrencesOfString:countryCode withString:@""];
  264. // }
  265. NSLog(@"countryCode:%@ languageCode : %@",countryCode, languageCode);
  266. ///当前APP使用的语言
  267. NSString *preferredLanguage = [[[NSBundle mainBundle] preferredLocalizations] firstObject];
  268. //获取设备当前地区的代码和APP语言环境
  269. NSString *localeIdentifier = [[NSLocale currentLocale] objectForKey:NSLocaleIdentifier];
  270. NSLog(@"preferredLanguage:%@ localeIdentifier : %@",preferredLanguage, localeIdentifier);
  271. //目前支持 中文(简体 繁体) 英文 日语(还没做)
  272. if([languageCode rangeOfString:preferredLanguage].location != NSNotFound){
  273. // if([preferredLanguage rangeOfString:@"ja"].location != NSNotFound){
  274. // //日文现在也显示英文
  275. // [self setDefaultEnglishFun];
  276. // }
  277. // else
  278. {
  279. [DDYLanguageTool ddy_SetLanguage:@"" complete:^(NSError *error) {
  280. // 刷新rootVC等
  281. }];
  282. }
  283. }
  284. else{
  285. [self setDefaultEnglishFun];
  286. }
  287. }
  288. #pragma mark 设置当前显示语言为中文
  289. - (void)setDefaultEnglishFun{
  290. //默认设为英文
  291. [DDYLanguageTool ddy_SetLanguage:@"en" complete:^(NSError *error) {
  292. // 刷新rootVC等
  293. }];
  294. }
  295. - (void)batteryLevelChanged:(NSNotification *)notification {
  296. // 获取当前设备的电池电量
  297. UIDevice *device = notification.object;
  298. float batteryLevel = device.batteryLevel;
  299. // 根据电量级别执行相应的操作
  300. if (batteryLevel < 0.2) {
  301. NSLog(@"Low battery level. Please charge the device.");
  302. } else if (batteryLevel < 0.5) {
  303. NSLog(@"Medium battery level.");
  304. } else {
  305. NSLog(@"High battery level.");
  306. }
  307. }
  308. - (void)handleCrashException:(NSString*)exceptionMessage exceptionCategory:(JJExceptionGuardCategory)exceptionCategory extraInfo:(nullable NSDictionary*)info{
  309. NSMutableString *totalLogstr = [NSMutableString new];
  310. if(exceptionMessage){
  311. [totalLogstr appendString:exceptionMessage];
  312. [totalLogstr appendString:@"\n\n\n"];
  313. }
  314. if(info){
  315. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info options:info error:nil];
  316. if(jsonData && jsonData.length>0){
  317. NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  318. if(jsonStr){
  319. [totalLogstr appendString:jsonStr];
  320. }
  321. }
  322. }
  323. //写日志
  324. if(totalLogstr && totalLogstr.length >0){
  325. [cachesFileManager writeCrashLogsWithMsg:totalLogstr];
  326. }
  327. }
  328. - (NSString*)NASShareFileService
  329. {
  330. //http://transfer.armclouding.com:10012/getFile?path=/sdcard/Download/mmexport1712039794930_4124382.png
  331. if(_NASShareFileService && _NASShareFileService.length >0){
  332. return _NASShareFileService;
  333. }
  334. if(_NASMsgMod){
  335. if([_NASMsgMod.data.domainName rangeOfString:@"http"].location != NSNotFound){
  336. _NASShareFileService = [[NSString alloc] initWithFormat:@"%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  337. //return [[NSString alloc] initWithFormat:@"%@:%@/",@"http://transfer.armclouding.com",@"10016"];
  338. //return [[NSString alloc] initWithFormat:@"%@:%@/",@"http://transfer.armclouding.com",_NASMsgMod.data.port];
  339. }
  340. else{
  341. _NASShareFileService = [[NSString alloc] initWithFormat:@"http://%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  342. //return [[NSString alloc] initWithFormat:@"http://%@:%@/",@"transfer.armclouding.com",@"10016"];
  343. //return [[NSString alloc] initWithFormat:@"http://%@:%@/",@"transfer.armclouding.com",_NASMsgMod.data.port];
  344. }
  345. //return [[NSString alloc] initWithFormat:@"%@getFile?path=",_NASMsgMod.data.baseUrl];
  346. //return [[NSString alloc] initWithFormat:@"%@/",_NASMsgMod.data.baseUrl];
  347. }
  348. return _NASShareFileService;
  349. }
  350. - (NSString*)NASFileByBoxService
  351. {
  352. //内网情况
  353. if([pingManager shareManager].isPingOk){
  354. if(NASFileByBoxServiceByPingok && NASFileByBoxServiceByPingok.length >0){
  355. return NASFileByBoxServiceByPingok;
  356. }
  357. NASFileByBoxServiceByPingok = [NSString stringWithFormat:@"http://%@:9888/",ksharedAppDelegate.DeviceThirdIdMod.data.ip];
  358. return NASFileByBoxServiceByPingok;
  359. }
  360. //外网情况
  361. if(_NASMsgMod){
  362. if(NASFileByBoxServiceByPingNot && NASFileByBoxServiceByPingNot.length >0){
  363. return NASFileByBoxServiceByPingNot;
  364. }
  365. if(!_NASMsgMod.data.domainName){
  366. return nil;
  367. }
  368. else if([_NASMsgMod.data.domainName rangeOfString:@"http"].location != NSNotFound){
  369. NASFileByBoxServiceByPingNot = [[NSString alloc] initWithFormat:@"%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  370. }
  371. else{
  372. NASFileByBoxServiceByPingNot = [[NSString alloc] initWithFormat:@"http://%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  373. }
  374. return NASFileByBoxServiceByPingNot;
  375. }
  376. return @"";
  377. }
  378. #pragma mark 更换设备 重新设置地址
  379. - (void)resetBoxNetUrlFun
  380. {
  381. _NASShareFileService = nil;
  382. NASFileByBoxServiceByPingok = nil;
  383. NASFileByBoxServiceByPingNot = nil;
  384. }
  385. - (void)imageLoadingSettings {
  386. [SDImageCache sharedImageCache].config.maxDiskAge = 3600 * 24 * 7;
  387. [SDImageCache sharedImageCache].config.maxMemoryCount = 1024 * 1024 * 20;
  388. [SDImageCache sharedImageCache].config.shouldCacheImagesInMemory = YES;
  389. //[SDImageCache sharedImageCache].config.shouldDecompressImages = NO;
  390. //[SDWebImageDownloader sharedDownloader].shouldDecompressImages = NO;
  391. [SDImageCache sharedImageCache].config.diskCacheReadingOptions = NSDataReadingMappedIfSafe;
  392. }
  393. @end