AppDelegate.m 19 KB

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