AppDelegate.m 19 KB

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