AppDelegate.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 "AFNetworkReachabilityManager.h"
  13. #import "PLeakSniffer.h"
  14. #import "connectDeviceManager.h"
  15. #import <Bugly/Bugly.h>
  16. #import <JJException/JJException.h>
  17. #import <WXApi.h>
  18. #import <TencentOpenAPI/QQApiInterface.h>
  19. #import <TencentOpenAPI/TencentOAuth.h>
  20. #import <SDWebImage/SDWebImage.h>
  21. @interface AppDelegate ()<JJExceptionHandle,WXApiDelegate>
  22. {
  23. CMMotionManager *cmManager;
  24. }
  25. @end
  26. @implementation AppDelegate
  27. + (AppDelegate*)sharedAppDelegate
  28. {
  29. static AppDelegate *appDelegate = nil;
  30. static dispatch_once_t onceToken;
  31. dispatch_once(&onceToken, ^{
  32. if (appDelegate == nil) {
  33. appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  34. }
  35. });
  36. return appDelegate;
  37. }
  38. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  39. //保护App,一般常见的问题不会导致闪退,增强App的健壮性,同时会将错误抛出来,根据每个App自身的日志渠道记录
  40. // [JJException configExceptionCategory:JJExceptionGuardAll];
  41. // [JJException startGuardException];
  42. // [JJException registerExceptionHandle:self];
  43. //
  44. // //Default value:NO no表示异常不退出 YES 表示退出 开发时应该设置为YES
  45. // JJException.exceptionWhenTerminate = YES;
  46. //test code
  47. // NSArray * arr = @[];
  48. // NSString *str = arr[2];
  49. [self setLanguagesFun];
  50. //设置默认值
  51. // self.couldPhone_W_PHONE = 720.0;
  52. // self.couldPhone_H_PHONE = 1280.0;
  53. self.couldPhone_W_PHONE = 1080.0;
  54. self.couldPhone_H_PHONE = 1920.0;
  55. [[UIButton appearance] setExclusiveTouch:YES];
  56. cmManager = [[CMMotionManager alloc] init];
  57. if (cmManager.isAccelerometerAvailable){
  58. HLog(@"\n-------摇一摇可用-----");
  59. }else{
  60. HLog(@"\n-------摇一摇不可用-----");
  61. }
  62. cmManager.accelerometerUpdateInterval = 0.1;
  63. [cmManager startAccelerometerUpdates];
  64. [cmManager startDeviceMotionUpdatesToQueue:[NSOperationQueue new] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
  65. // CMRotationRate rotationRate = motion.rotationRate;
  66. // CGFloat rotationRatex = rotationRate.x;
  67. // CGFloat rotationRatey = rotationRate.y;
  68. // CGFloat rotationRatez = rotationRate.z;
  69. CMAcceleration accrleration = motion.gravity;
  70. CGFloat rotationGravityz = accrleration.z;
  71. //HLog(@"rotationRatey: %f",rotationRatey)
  72. //HLog(@"rotationGravityz: %f",rotationGravityz)
  73. //if (rotationRatey > 7){
  74. if (rotationGravityz > 0.85){
  75. BOOL haveOpenMask = [HWDataManager getBoolWithKey:Consn_Fanzhuan_Exit_app_Open];
  76. BOOL isPrivacyMode = [connectDeviceManager shareInstance].DeviceThirdIdMod.data.isPrivacyMode;
  77. if (haveOpenMask && isPrivacyMode){
  78. exit(0);/*强制退出app*/
  79. }
  80. }
  81. }];
  82. // [[ShearDeviceUDPManager shareInstance] startShearchDevice];
  83. // [[ShearDeviceUDPManager shareInstance] shearchDeviceLoop];
  84. //启动后台保活
  85. [AudioSessionObject shareManager];
  86. [self MonitorNetworkChangesFun];
  87. #ifdef DEBUG
  88. [[PLeakSniffer sharedInstance] installLeakSniffer];
  89. #else
  90. [Bugly startWithAppId:@"179559a521"];
  91. #endif
  92. [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleDark)];
  93. [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
  94. [[UIDevice currentDevice] batteryLevel];
  95. // 监听电池电量变化通知
  96. //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
  97. //微信注册
  98. [WXApi registerApp:WXAPPid universalLink:wxuniversalLink];
  99. [TencentOAuth setIsUserAgreedAuthorization:YES];
  100. TencentOAuth *tencentOAuth =[[TencentOAuth alloc] initWithAppId:QQAPPid andUniversalLink:QQUniversalLink andDelegate:self];
  101. [self imageLoadingSettings];
  102. return YES;
  103. }
  104. /// 在这里写支持的旋转方向,为了防止横屏方向,应用启动时候界面变为横屏模式
  105. - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  106. return UIInterfaceOrientationMaskPortrait;
  107. }
  108. #pragma mark - UISceneSession lifecycle
  109. - (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
  110. // Called when a new scene session is being created.
  111. // Use this method to select a configuration to create the new scene with.
  112. return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
  113. }
  114. - (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
  115. // Called when the user discards a scene session.
  116. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  117. // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  118. }
  119. - (void)applicationWillEnterForeground:(UIApplication *)application {
  120. // 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.
  121. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  122. NSString *orderNumber = [HWDataManager getStringWithKey:Const_AirpayOrWXorderNum];
  123. if (orderNumber && ![orderNumber isEqualToString:@""])
  124. {
  125. [[NSNotificationCenter defaultCenter] postNotificationName:NotNameAirpayOrWXorderNum object:orderNumber];
  126. }
  127. });
  128. }
  129. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
  130. return [WXApi handleOpenURL:url delegate:self];
  131. }
  132. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
  133. if (YES == [TencentOAuth CanHandleOpenURL:url])
  134. {
  135. return [TencentOAuth HandleOpenURL:url];
  136. }
  137. return [WXApi handleOpenURL:url delegate:self];
  138. }
  139. - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
  140. {
  141. if([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
  142. NSURL *url = userActivity.webpageURL;
  143. if(url && [TencentOAuth CanHandleUniversalLink:url]) {
  144. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"CI UniversalLink" message:url.description delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
  145. [alertView show];
  146. //[QQApiInterface handleOpenUniversallink:url delegate:(id<QQApiInterfaceDelegate>)[QQApiShareEntry class]];
  147. return [TencentOAuth HandleUniversalLink:url];
  148. }
  149. }
  150. return [WXApi handleOpenUniversalLink:userActivity delegate:self];
  151. }
  152. #pragma mark 监听网络变化
  153. -(void)MonitorNetworkChangesFun
  154. {
  155. [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  156. HLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
  157. [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkChangeNotification object:nil];
  158. }];
  159. [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  160. }
  161. #pragma mark 多国语言相关
  162. -(void)setLanguagesFun{
  163. NSArray *arLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
  164. NSLog(@"arLanguages:%@",arLanguages);
  165. ///获取设备当前地区的代码和APP语言环境
  166. NSString *languageCode = [NSLocale preferredLanguages][0];
  167. // 获取国际通用国家地区代码(应该和手机本身有关)
  168. NSString *countryCode = [NSString stringWithFormat:@"-%@", [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]];
  169. // if (languageCode) {
  170. // languageCode = [languageCode stringByReplacingOccurrencesOfString:countryCode withString:@""];
  171. // }
  172. NSLog(@"countryCode:%@ languageCode : %@",countryCode, languageCode);
  173. ///当前APP使用的语言
  174. NSString *preferredLanguage = [[[NSBundle mainBundle] preferredLocalizations] firstObject];
  175. //获取设备当前地区的代码和APP语言环境
  176. NSString *localeIdentifier = [[NSLocale currentLocale] objectForKey:NSLocaleIdentifier];
  177. NSLog(@"preferredLanguage:%@ localeIdentifier : %@",preferredLanguage, localeIdentifier);
  178. //目前支持 中文(简体 繁体) 英文 日语(还没做)
  179. if([languageCode rangeOfString:preferredLanguage].location != NSNotFound){
  180. // if([preferredLanguage rangeOfString:@"ja"].location != NSNotFound){
  181. // //日文现在也显示英文
  182. // [self setDefaultEnglishFun];
  183. // }
  184. // else
  185. {
  186. [DDYLanguageTool ddy_SetLanguage:@"" complete:^(NSError *error) {
  187. // 刷新rootVC等
  188. }];
  189. }
  190. }
  191. else{
  192. [self setDefaultEnglishFun];
  193. }
  194. }
  195. #pragma mark 设置当前显示语言为中文
  196. - (void)setDefaultEnglishFun{
  197. //默认设为英文
  198. [DDYLanguageTool ddy_SetLanguage:@"en" complete:^(NSError *error) {
  199. // 刷新rootVC等
  200. }];
  201. }
  202. - (void)batteryLevelChanged:(NSNotification *)notification {
  203. // 获取当前设备的电池电量
  204. UIDevice *device = notification.object;
  205. float batteryLevel = device.batteryLevel;
  206. // 根据电量级别执行相应的操作
  207. if (batteryLevel < 0.2) {
  208. NSLog(@"Low battery level. Please charge the device.");
  209. } else if (batteryLevel < 0.5) {
  210. NSLog(@"Medium battery level.");
  211. } else {
  212. NSLog(@"High battery level.");
  213. }
  214. }
  215. - (void)handleCrashException:(NSString*)exceptionMessage exceptionCategory:(JJExceptionGuardCategory)exceptionCategory extraInfo:(nullable NSDictionary*)info{
  216. NSMutableString *totalLogstr = [NSMutableString new];
  217. if(exceptionMessage){
  218. [totalLogstr appendString:exceptionMessage];
  219. [totalLogstr appendString:@"\n\n\n"];
  220. }
  221. if(info){
  222. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:info options:info error:nil];
  223. if(jsonData && jsonData.length>0){
  224. NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  225. if(jsonStr){
  226. [totalLogstr appendString:jsonStr];
  227. }
  228. }
  229. }
  230. //写日志
  231. if(totalLogstr && totalLogstr.length >0){
  232. [cachesFileManager writeCrashLogsWithMsg:totalLogstr];
  233. }
  234. }
  235. - (NSString*)NASFileService
  236. {
  237. //http://transfer.armclouding.com:10012/getFile?path=/sdcard/Download/mmexport1712039794930_4124382.png
  238. if(_NASMsgMod){
  239. if([_NASMsgMod.data.domainName rangeOfString:@"http"].location != NSNotFound){
  240. return [[NSString alloc] initWithFormat:@"%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  241. //return [[NSString alloc] initWithFormat:@"%@:%@/",@"http://transfer.armclouding.com",@"10016"];
  242. //return [[NSString alloc] initWithFormat:@"%@:%@/",@"http://transfer.armclouding.com",_NASMsgMod.data.port];
  243. }
  244. else{
  245. return [[NSString alloc] initWithFormat:@"http://%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  246. //return [[NSString alloc] initWithFormat:@"http://%@:%@/",@"transfer.armclouding.com",@"10016"];
  247. //return [[NSString alloc] initWithFormat:@"http://%@:%@/",@"transfer.armclouding.com",_NASMsgMod.data.port];
  248. }
  249. //return [[NSString alloc] initWithFormat:@"%@getFile?path=",_NASMsgMod.data.baseUrl];
  250. //return [[NSString alloc] initWithFormat:@"%@/",_NASMsgMod.data.baseUrl];
  251. }
  252. return nil;
  253. }
  254. - (NSString*)NASFileByBoxService
  255. {
  256. if([connectDeviceManager shareInstance].isPingOk){
  257. return [NSString stringWithFormat:@"http://%@:9888",[connectDeviceManager shareInstance].DeviceThirdIdMod.data.ip];
  258. }
  259. if(_NASMsgMod){
  260. if([_NASMsgMod.data.domainName rangeOfString:@"http"].location != NSNotFound){
  261. return [[NSString alloc] initWithFormat:@"%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  262. }
  263. else{
  264. return [[NSString alloc] initWithFormat:@"http://%@:%@/",_NASMsgMod.data.domainName,_NASMsgMod.data.port];
  265. }
  266. }
  267. return @"";
  268. }
  269. - (void)imageLoadingSettings {
  270. [SDImageCache sharedImageCache].config.maxDiskAge = 3600 * 24 * 7;
  271. [SDImageCache sharedImageCache].config.maxMemoryCount = 1024 * 1024 * 20;
  272. [SDImageCache sharedImageCache].config.shouldCacheImagesInMemory = NO;
  273. //[SDImageCache sharedImageCache].config.shouldDecompressImages = NO;
  274. //[SDWebImageDownloader sharedDownloader].shouldDecompressImages = NO;
  275. [SDImageCache sharedImageCache].config.diskCacheReadingOptions = NSDataReadingMappedIfSafe;
  276. }
  277. @end