AppDelegate.m 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. //
  2. // AppDelegate.m
  3. // aiim
  4. //
  5. // Created by gan on 2025/2/27.
  6. //
  7. #import "AppDelegate.h"
  8. #import "UDManager.h"
  9. #import <UserNotifications/UserNotifications.h>
  10. #import <PushKit/PushKit.h>
  11. #import "CallKit/CallKit.h"
  12. #import <AFNetworking/AFNetworkReachabilityManager.h>
  13. #import "UserNetApi.h"
  14. #import "CryptoAES.h"
  15. #import "GWebSocket.h"
  16. #import "GDBManager.h"
  17. #import "APPLocker.h"
  18. #import "JSGController.h"
  19. #import "LoginStateManager.h"
  20. #import "FloatingWindow.h"
  21. #import "ChatIndexController.h"
  22. #import "ChatController.h"
  23. #import "ChatListStore.h"
  24. #import "ChatsStore.h"
  25. #import "OSSManager.h"
  26. #import <Bugly/Bugly.h>
  27. #ifdef DEBUG
  28. #import <DoraemonKit/DoraemonManager.h>
  29. #endif
  30. @import JitsiMeetSDK;
  31. @interface AppDelegate ()<UNUserNotificationCenterDelegate,PKPushRegistryDelegate,CXProviderDelegate>
  32. {
  33. BOOL _isReachable;
  34. }
  35. @property (nonatomic, strong) CXProvider *callProvider;
  36. @property (nonatomic) NSUUID *uuid;
  37. @property (nonatomic) NSDictionary *msg;
  38. @property (strong, nonatomic) NSString *bgMark;
  39. @property (nonatomic) BOOL isTokenCleared;
  40. @property (strong, nonatomic) FloatingWindow *floatWindow;
  41. @property (nonatomic, strong) JSGController * _Nullable jsyuyinctr;
  42. @property (nonatomic) BOOL isNotification;
  43. @property (nonatomic, assign) NSInteger badgeCount;
  44. @property (nonatomic, assign) NSInteger addFriendBadgeCount;
  45. @end
  46. @implementation AppDelegate
  47. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  48. // Override point for customization after application launch.
  49. app = self;
  50. BuglyConfig *config = [[BuglyConfig alloc] init];
  51. config.reportLogLevel = BuglyLogLevelVerbose;
  52. [Bugly startWithAppId:@"1d9e6b546a" config:config];
  53. self.isJitsiMeet=false;
  54. _isNotification=false;
  55. self.shouldShowLock = YES;
  56. self.bgMark=@"";
  57. [self initJSMSDK];
  58. [self setupListener];
  59. [self checkLoginState:launchOptions];
  60. [self registerPushright];
  61. [self setupCallProvider];
  62. [self startNetworkReachability];
  63. _isTokenCleared=YES;
  64. _floatWindow = [[FloatingWindow alloc] initWithFrame:self.window.bounds];
  65. [_floatWindow hide];
  66. self.bgMark = @"";
  67. NSLog(@"didFinishLaunchingWithOptions------");
  68. AVAudioSession *session = [AVAudioSession sharedInstance];
  69. [session setCategory:AVAudioSessionCategoryPlayAndRecord mode:AVAudioSessionModeVoiceChat options:AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP | AVAudioSessionCategoryOptionAllowAirPlay error:nil];
  70. [session setActive:YES error:nil];
  71. #ifdef DEBUG
  72. //默认
  73. [[DoraemonManager shareInstance] install];
  74. // 或者使用传入位置,解决遮挡关键区域,减少频繁移动
  75. //[[DoraemonManager shareInstance] installWithStartingPosition:CGPointMake(66, 66)];
  76. #endif
  77. return YES;
  78. }
  79. -(void)applicationDidBecomeActive:(UIApplication *)application{
  80. NSLog(@"applicationDidBecomeActive");
  81. if(self.isLogin){
  82. [self sartWebsocket];
  83. if(self.isJitsiMeet){
  84. [_floatWindow viewInFload:0];
  85. }
  86. [self showLockScreen];
  87. if(!_isNotification){
  88. if ([[self.window jk_currentViewController] isKindOfClass:UITabBarController.class]){
  89. UITabBarController * tabbarVc= (UITabBarController *)[self.window jk_currentViewController];
  90. if (tabbarVc.selectedIndex==0) {
  91. ChatIndexController * chatListVc = tabbarVc.viewControllers[0];
  92. if (chatListVc) {
  93. [chatListVc reloadList];
  94. }
  95. }
  96. }
  97. else{
  98. [Bugly reportException:[NSException exceptionWithName:@"applicationDidBecomeActive1" reason:@"1" userInfo:nil]];
  99. if ([[self.window jk_currentViewController] isKindOfClass:ChatController.class]) {
  100. ChatController * currentChatVc = (ChatController *)[self.window jk_currentViewController];
  101. [currentChatVc reloadAllData];
  102. [Bugly reportException:[NSException exceptionWithName:@"applicationDidBecomeActive2" reason:@"2" userInfo:nil]];
  103. }
  104. }
  105. }
  106. }
  107. }
  108. -(void)applicationDidEnterBackground:(UIApplication *)application{
  109. NSLog(@"applicationDidEnterBackground");
  110. _isNotification=false;
  111. // [self endWebsocket];
  112. __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  113. [application endBackgroundTask:bgTask];
  114. bgTask = UIBackgroundTaskInvalid;
  115. }];
  116. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  117. // 在这里保持任务运行或等待事件,例如等待来电等。
  118. [application endBackgroundTask:bgTask];
  119. bgTask = UIBackgroundTaskInvalid;
  120. });
  121. // 应用进入后台时标记需要显示锁屏
  122. if(self.isJitsiMeet == YES){
  123. [self.window endEditing:YES];
  124. }
  125. else{
  126. if ([[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  127. self.shouldShowLock = YES;
  128. }
  129. }
  130. }
  131. + (instancetype)sharedInstance {
  132. return app;
  133. }
  134. -(void)initJSMSDK{
  135. JitsiMeetConferenceOptions *defaultOptions
  136. = [JitsiMeetConferenceOptions fromBuilder:^(JitsiMeetConferenceOptionsBuilder *builder) {
  137. builder.serverURL = [NSURL URLWithString:JitsiMeetSV];
  138. [builder setFeatureFlag:@"welcomepage.enabled" withBoolean:NO];
  139. [builder setFeatureFlag:@"prejoinPage.enabled" withBoolean:NO];
  140. //媒体流优化
  141. builder.audioMuted = NO; // 提前初始化音频模块
  142. builder.videoMuted = NO; // 提前初始化视频模块
  143. //禁用非必要功能(减少初始化负载)
  144. [builder setFeatureFlag:@"add-people.enabled" withBoolean:NO];
  145. [builder setFeatureFlag:@"invite.enabled" withBoolean:NO];
  146. [builder setFeatureFlag:@"live-streaming.enabled" withBoolean:NO];
  147. [builder setFeatureFlag:@"video-share.enabled" withBoolean:NO];
  148. [builder setFeatureFlag:@"call-integration.enabled" withBoolean:NO];
  149. [builder setFeatureFlag:@"startWithAudioMuted" withBoolean:NO];
  150. [builder setFeatureFlag:@"recording.enabled" withBoolean:NO];
  151. [builder setFeatureFlag:@"kick-out.enabled" withBoolean:NO];
  152. [builder setFeatureFlag:@"security-options.enabled" withBoolean:NO];
  153. //
  154. // //网络传输层加速
  155. // [builder setConfigOverride:@"disableSimulcast" withBoolean:YES];
  156. // [builder setFeatureFlag:@"reconnect.enabled" withBoolean:YES];
  157. // [builder setFeatureFlag:@"websocket-keep-alive.enabled" withBoolean:YES];
  158. // [builder setFeatureFlag:@"network-monitor.enabled" withBoolean:YES];
  159. // [builder setConfigOverride:@"iceTransportPolicy" withValue:@"relay"];
  160. // // 界面渲染加速
  161. // [builder setFeatureFlag:@"filmstrip.enabled" withBoolean:NO];
  162. // [builder setFeatureFlag:@"tile-view.enabled" withBoolean:NO];
  163. //
  164. // [builder setFeatureFlag:@"pip.enabled" withBoolean:NO];
  165. // [builder setFeatureFlag:@"chat.enabled" withBoolean:NO];
  166. [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
  167. }];
  168. [JitsiMeet sharedInstance].defaultConferenceOptions = defaultOptions;
  169. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  170. _jsyuyinctr = [board instantiateViewControllerWithIdentifier:@"JSGController"];
  171. _jsyuyinctr.modalPresentationStyle = UIModalPresentationFullScreen;
  172. }
  173. -(void)setupListener{
  174. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLoginSucc) name:nkonLoginSucc object:nil];
  175. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onLogoutSucc) name:nkonLogoutSucc object:nil];
  176. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addFriend) name:nkonAddFriendNote object:nil];;
  177. }
  178. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  179. NSLog(@"Failed to get token, error: %@", error);
  180. }
  181. #pragma mark push token voip token
  182. -(void)registerPushright{
  183. // 请求推送权限
  184. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  185. center.delegate = self; // 设置代理以处理通知相关事件
  186. [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionProvidesAppNotificationSettings) completionHandler:^(BOOL granted, NSError * _Nullable error) {
  187. if (granted) {
  188. // 用户授权成功
  189. dispatch_async(dispatch_get_main_queue(), ^{
  190. [[UIApplication sharedApplication] registerForRemoteNotifications];
  191. });
  192. } else {
  193. // 用户授权失败
  194. }
  195. }];
  196. PKPushRegistry *registry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
  197. registry.delegate = self;
  198. registry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
  199. }
  200. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  201. // 将NSData转换为NSString以便于传输或存储
  202. NSRange range = NSMakeRange(0, 16); // 例如,从索引0开始,获取前10个字节
  203. NSData *subData1 = [deviceToken subdataWithRange:range];
  204. range = NSMakeRange(16, 16);
  205. NSData *subData2 = [deviceToken subdataWithRange:range];
  206. range = NSMakeRange(24, 32);
  207. NSString *token1=[[subData1 description] substringWithRange:range];
  208. NSString *token2=[[subData2 description] substringWithRange:range];
  209. NSString *token = [NSString stringWithFormat:@"%@%@",token1,token2];
  210. NSLog(@"%@",token);
  211. // 将token发送到你的服务器或其他需要的地方
  212. [UDManager.shareInstance setSDManager:token key:dkpushtoken];
  213. NSString *bgMark = [NSString stringWithFormat:@"推送token:%ld",token.length];
  214. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  215. if(self.isLogin){
  216. [self updivicetoken];
  217. }
  218. }
  219. #pragma mark login sttate
  220. - (void)checkLoginState:(NSDictionary *)launchOptions{
  221. [[LoginStateManager sharedManager] getUserInfo];
  222. [LoginStateManager sharedManager].checkLoginState = ^(BOOL isLogin) {
  223. if (isLogin) {
  224. self.isLogin =TRUE;
  225. [self updivicetoken];
  226. [self updiviceVoIPtoken];
  227. [self sartWebsocket];
  228. [self openFMDB];
  229. [self openMainController];
  230. // 检查是否需要显示启动锁屏
  231. if ([[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  232. [self showLockScreen];
  233. }
  234. else{
  235. self.shouldShowLock = NO;
  236. }
  237. }else{
  238. [self openLoginController];
  239. }
  240. };
  241. }
  242. -(void)updivicetoken{
  243. NSString *token =[UDManager.shareInstance getSDManager:dkpushtoken];
  244. NSDictionary *usinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
  245. NSLog(@"dkpushtoken:%@",token);
  246. NSDictionary *ud=@{
  247. @"registrationId": token?:@"",
  248. @"userId":usinfo[@"id"]?:@"",
  249. @"platformType":@"i"
  250. };
  251. NSString *bgMark = [NSString stringWithFormat:@"上传推送token:%ld",token.length];
  252. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  253. [UserNetApi setUserinfo:ud succ:^(int code, NSDictionary * res) {
  254. self->_isTokenCleared=NO;
  255. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:res options:0 error:nil];
  256. if (!jsonData) {
  257. NSLog(@"Got an error:");
  258. } else {
  259. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  260. NSLog(@"%@", jsonString); // 输出:{"name":"John","age":25}
  261. }
  262. } fail:^(NSError * _Nonnull error) {
  263. NSLog(@"--%@",error);
  264. }];
  265. }
  266. -(void)updiviceVoIPtoken{
  267. NSString *token =[UDManager.shareInstance getSDManager:dkvoiptoken];
  268. NSDictionary *usinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
  269. NSLog(@"dkvoiptoken:%@",token);
  270. NSString *bgMark = [NSString stringWithFormat:@"上传 voip 推送token:%ld",token.length];
  271. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  272. if([token isKindOfClass:[NSNull class]]){
  273. return;
  274. }
  275. NSDictionary *ud=@{
  276. @"voipTk": token?:@"",
  277. @"userId":usinfo[@"id"]?:@"",
  278. @"platformType":@"i"
  279. };
  280. [UserNetApi setUserinfo:ud succ:^(int code, NSDictionary * res) {
  281. NSLog(@"updiviceVoIPtoken:%@",[res description]);
  282. self->_isTokenCleared=NO;
  283. } fail:^(NSError * _Nonnull error) {
  284. NSLog(@"--%@",error);
  285. }];
  286. }
  287. - (void)addFriend{
  288. self.addFriendBadgeCount++;
  289. NSLog(@"addFriend------------:%ld", self.addFriendBadgeCount);
  290. [self updateTabBarBadgeValueAtIndex:1 badgeCount:self.addFriendBadgeCount];
  291. [self sendAddFreindNotice];
  292. [self updateApplicationIconBadgeNumber];
  293. }
  294. - (void)sendAddFreindNotice {
  295. // 发送本地通知
  296. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  297. content.title = @"好友申请";
  298. content.body = @"您收到了新的好友申请";
  299. content.sound = [UNNotificationSound defaultSound];
  300. content.badge = @(self.addFriendBadgeCount);
  301. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
  302. NSString *identifier = [NSString stringWithFormat:@"FriendRequest_%@", [[NSUUID UUID] UUIDString]];
  303. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  304. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  305. if (error) {
  306. NSLog(@"发送本地通知失败: %@", error);
  307. } else {
  308. NSLog(@"发送本地通知成功");
  309. }
  310. }];
  311. }
  312. - (void)updateApplicationIconBadgeNumber {
  313. NSInteger total = self.badgeCount + self.addFriendBadgeCount;
  314. if (@available(iOS 16.0, *)) {
  315. [[UNUserNotificationCenter currentNotificationCenter] setBadgeCount:total withCompletionHandler:^(NSError * _Nullable error) {
  316. if (error) {
  317. NSLog(@"设置消息未读数 error: %@", error);
  318. }
  319. }];
  320. } else {
  321. // Fallback on earlier versions
  322. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:total];
  323. }
  324. }
  325. - (void)resetAddFriendBadgeCount {
  326. self.addFriendBadgeCount = 0;
  327. [self updateTabBarBadgeValueAtIndex:1 badgeCount:0];
  328. [self updateApplicationIconBadgeNumber];
  329. }
  330. - (void)resetBadgeCount {
  331. self.badgeCount = 0;
  332. [self updateApplicationIconBadgeNumber];
  333. }
  334. - (void)updateTabBarBadgeValueAtIndex:(NSInteger)index badgeCount:(NSInteger)badgeCount {
  335. UITabBarController * tabbarVc = (UITabBarController *)self.window.rootViewController;
  336. if (![tabbarVc isKindOfClass:[UITabBarController class]]) {
  337. return;
  338. }
  339. if(index < 0 || index >= tabbarVc.tabBar.items.count){
  340. return;
  341. }
  342. UITabBarItem *tabBarItem = tabbarVc.tabBar.items[index];
  343. NSString *badgeValue = badgeCount > 0 ? [NSString stringWithFormat:@"%ld", badgeCount] : nil;
  344. badgeValue = badgeValue.length > 2 ? @"99+" : badgeValue;
  345. tabBarItem.badgeValue = badgeValue;
  346. }
  347. - (void)updateBadgeCount:(NSInteger)badgeCount {
  348. self.badgeCount = badgeCount;
  349. [self updateApplicationIconBadgeNumber];
  350. }
  351. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  352. NSLog(@"Received notification: %@", userInfo);
  353. NSDictionary *temp =userInfo[@"imMsg"];
  354. if(temp){
  355. if ([temp jk_hasKey:@"addFriend"]) {
  356. [self addFriend];
  357. }
  358. NSDictionary *msg =temp[@"message"];
  359. NSString *msgtype=msg[@"msgtype"];
  360. if([msgtype isEqualToString:@"close"]){
  361. if(self.uuid!=nil){
  362. NSString *fromId = self.msg[@"fromId"];
  363. if ( [fromId isEqualToString:msg[@"fromId"]]) {
  364. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  365. self.uuid = nil;
  366. self.msg =nil;
  367. }
  368. }
  369. }
  370. }
  371. // 处理推送消息,例如更新UI或处理数据等
  372. completionHandler(UIBackgroundFetchResultNewData);
  373. }
  374. #pragma mark - PKPushRegistryDelegate
  375. - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type {
  376. // 处理推送凭证更新,例如保存 token 到服务器
  377. NSLog(@"Credentials updated: %@", credentials.token);
  378. NSData *deviceToken = (NSData *)credentials.token;
  379. NSRange range = NSMakeRange(0, 16); // 例如,从索引0开始,获取前10个字节
  380. NSData *subData1 = [deviceToken subdataWithRange:range];
  381. range = NSMakeRange(16, 16);
  382. NSData *subData2 = [deviceToken subdataWithRange:range];
  383. range = NSMakeRange(24, 32);
  384. //NSLog(@"subData1: %@",subData1);
  385. //NSLog(@"subData2: %@",subData2);
  386. NSString *token1=[[subData1 description] substringWithRange:range];
  387. NSString *token2=[[subData2 description] substringWithRange:range];
  388. NSString *token = [NSString stringWithFormat:@"%@%@",token1,token2];
  389. NSLog(@"%@",token);
  390. //将token发送到你的服务器或其他需要的地方
  391. NSString *bgMark = [NSString stringWithFormat:@"voip token:%ld",token.length];
  392. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  393. [UDManager.shareInstance setSDManager:token key:dkvoiptoken];
  394. if(self.isLogin){
  395. [self updiviceVoIPtoken];
  396. }
  397. }
  398. - (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion{
  399. NSDictionary * temp =payload.dictionaryPayload;
  400. temp =temp[@"business"];
  401. temp=temp[@"incomingCallParams"];
  402. NSString *name =temp[@"localizedCallerName"];
  403. NSLog(@"name:%@",name);
  404. temp =payload.dictionaryPayload;
  405. temp =temp[@"imMsg"];
  406. if(self.uuid!=nil||self.isJitsiMeet){//通知对方正忙,功能需要补上
  407. [self isBUSYNow:temp[@"message"]];
  408. return;
  409. }
  410. self.msg = temp[@"message"];
  411. NSLog(@"self.msg-----:%@",self.msg);
  412. CXCallUpdate * callUpdate = [[CXCallUpdate alloc]init];
  413. callUpdate.supportsGrouping = YES;
  414. callUpdate.supportsDTMF = YES;
  415. callUpdate.hasVideo = YES;
  416. callUpdate.supportsHolding = YES;
  417. [callUpdate setLocalizedCallerName:name];
  418. CXHandle * handle = [[CXHandle alloc]initWithType:CXHandleTypePhoneNumber value:@""];
  419. callUpdate.remoteHandle = handle;
  420. self.uuid = [NSUUID UUID];
  421. [self.callProvider reportNewIncomingCallWithUUID:self.uuid update:callUpdate completion:^(NSError * _Nullable error) {
  422. NSLog(@"%@",error);
  423. }];
  424. completion();
  425. }
  426. -(void)isBUSYNow:(NSDictionary *)msg{
  427. NSDate *now = [NSDate date];
  428. NSTimeInterval trt = [now timeIntervalSince1970];
  429. NSInteger time = trt*1000;
  430. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  431. NSDictionary *callMsg = @{
  432. @"code":SendCode_WEBRTC_DFBUSY,
  433. @"message": @{
  434. @"chatId":msg[@"fromId"],
  435. @"fromId":msg[@"chatId"],
  436. @"type":@"0",
  437. @"messageType":MessageType_DFBUSY,
  438. @"timestamp":strtime,
  439. @"payload":@""
  440. }
  441. };
  442. NSError *error;
  443. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
  444. if (!jsonData) {
  445. NSLog(@"Got an error: %@", error);
  446. } else {
  447. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  448. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  449. [GWebSocket.shareInstance sendMsg:jsonString];
  450. }
  451. }
  452. #pragma mark - CXProviderDelegate Methods
  453. - (void)setupCallProvider {
  454. // 创建配置对象
  455. CXProviderConfiguration *config = [[CXProviderConfiguration alloc] init];
  456. config.supportsVideo = YES; // 是否支持视频通话
  457. config.maximumCallGroups = 1; // 最大通话组数
  458. config.maximumCallsPerCallGroup = 1; // 每个通话组的最大通话数
  459. config.supportedHandleTypes = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:CXHandleTypeGeneric],[NSNumber numberWithInt:CXHandleTypePhoneNumber], nil];//[NSSet setWithArray:@[CXHandleTypePhoneNumber]]; // 支持的号码类型
  460. config.iconTemplateImageData = UIImagePNGRepresentation([UIImage imageNamed:@"AppIcon"]); // 应用图标
  461. config.ringtoneSound = @"ringtone.aiff"; // 铃声文件(可选)
  462. // 创建CXProvider实例
  463. self.callProvider = [[CXProvider alloc] initWithConfiguration:config];
  464. [self.callProvider setDelegate:self queue:nil];
  465. //self.callRoomMap = [NSMutableDictionary dictionary];
  466. }
  467. - (void)providerDidReset:(CXProvider *)provider {
  468. NSLog(@"Provider reset");
  469. }
  470. - (void)provider:(CXProvider *)provider performStartCallAction:(CXStartCallAction *)action {
  471. // 开始通话的逻辑,如连接服务器等
  472. NSLog(@"performStartCallAction:%@",action);
  473. [action fulfill]; // 当通话开始时调用此方法完成action
  474. }
  475. -(void)provider:(CXProvider *)provider performAnswerCallAction:(CXAnswerCallAction *)action{
  476. [self reciveVoip];
  477. //使用GCD创建一个在3秒后执行的定时器
  478. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  479. NSLog(@"performAnswerCallAction:%@",action);
  480. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
  481. // 应用已经解锁并且在前台
  482. if(self.uuid){
  483. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  484. self.msg = nil;
  485. self.uuid = nil;
  486. }
  487. }
  488. });
  489. }
  490. -(void)provider:(CXProvider *)provider timedOutPerformingAction:(CXAction *)action{
  491. if (!self.uuid) {
  492. return;
  493. }
  494. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  495. self.msg = nil;
  496. self.uuid = nil;
  497. NSLog(@"timedOutPerformingAction:%@",action);
  498. }
  499. - (void)provider:(CXProvider *)provider performEndCallAction:(CXEndCallAction *)action {
  500. // 挂断电话的逻辑,如断开服务器连接等
  501. NSLog(@"performEndCallAction:%@",action);
  502. NSDate *now = [NSDate date];
  503. NSTimeInterval trt = [now timeIntervalSince1970];
  504. NSInteger time = trt*1000;
  505. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  506. NSDictionary *callMsg = @{
  507. @"code":@"9",
  508. @"message": @{
  509. @"chatId":self.msg[@"fromId"],
  510. @"fromId":self.msg[@"chatId"],
  511. @"type":@"0",
  512. @"msgtype":@"close",
  513. @"timestamp":strtime,
  514. @"payload":self.msg[@"payload"]
  515. }
  516. };
  517. NSError *error;
  518. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
  519. if (!jsonData) {
  520. NSLog(@"Got an error: %@", error);
  521. } else {
  522. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  523. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  524. [GWebSocket.shareInstance sendMsg:jsonString];
  525. }
  526. self.uuid = nil;
  527. self.msg =nil;
  528. [action fulfill]; // 当通话结束时调用此方法完成action
  529. }
  530. -(void)reciveVoip{
  531. NSLog(@"reciveVoip-------------1");
  532. if(self.msg){
  533. NSNumber *conetType = self.msg[@"conetType"];
  534. NSLog(@"vidio:%@",self.msg[@"payload"]);
  535. BOOL audioOnly = YES;
  536. if(conetType.boolValue){
  537. audioOnly = NO;
  538. }
  539. else{
  540. audioOnly = YES;
  541. }
  542. [self startJSCall:self.msg[@"fromId"] room:self.msg[@"payload"] isCaller:NO audioOnly:audioOnly];
  543. }
  544. }
  545. //开启悬浮窗拨打方式
  546. -(void)startJSCall:(NSString *_Nonnull)chatId room:(NSString *_Nonnull)roomId isCaller:(BOOL)isCaller audioOnly:(BOOL)audioOnly{
  547. self.isJitsiMeet = YES;
  548. if(_jsyuyinctr){
  549. _jsyuyinctr.chatId = chatId.copy;
  550. _jsyuyinctr.room = roomId.copy;
  551. _jsyuyinctr.audioOnly = audioOnly;
  552. _jsyuyinctr.isCaller = isCaller;
  553. }
  554. else{
  555. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  556. _jsyuyinctr = [board instantiateViewControllerWithIdentifier:@"JSGController"];
  557. _jsyuyinctr.modalPresentationStyle = UIModalPresentationFullScreen;
  558. _jsyuyinctr.chatId = chatId.copy;
  559. _jsyuyinctr.room = roomId.copy;
  560. _jsyuyinctr.audioOnly = audioOnly;
  561. _jsyuyinctr.isCaller = isCaller;
  562. }
  563. NSLog(@"startJSCall roomId:%@",roomId);
  564. [_floatWindow showView:_jsyuyinctr.view];
  565. [_jsyuyinctr startJitsiMeetCall];
  566. [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
  567. }
  568. -(void)floadinSmWindow:(NSInteger )type{
  569. if(type!=0){
  570. [_floatWindow viewInFload:type];
  571. }
  572. }
  573. +(void)closeVoip{
  574. if(app.uuid!=nil){
  575. [app.callProvider reportCallWithUUID:app.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  576. app.uuid = nil;
  577. app.msg =nil;
  578. }
  579. }
  580. +(void)JitsiMeetState:(BOOL)state{
  581. app.isJitsiMeet=state;
  582. if(!state){
  583. if(app.shouldShowLock){
  584. [app showLockScreen];
  585. }
  586. else{
  587. [app.floatWindow hide];
  588. }
  589. }
  590. }
  591. +(void)unlockAPP{
  592. app.shouldShowLock=NO;
  593. }
  594. +(void)changeFloadViewState:(BOOL)state{
  595. if (state) {
  596. [app.floatWindow hide];
  597. }
  598. else{
  599. if ([[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  600. [app.floatWindow show:1];
  601. }
  602. }
  603. }
  604. #pragma mark 用户点击消息推送或滑动
  605. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  606. completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner |
  607. UNNotificationPresentationOptionSound |
  608. UNNotificationPresentationOptionBadge);
  609. }
  610. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
  611. // 处理用户对通知的响应(点击、滑动等)
  612. if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {
  613. // 用户点击了通知
  614. NSDictionary *userInfo = response.notification.request.content.userInfo;
  615. [self handleNotification:userInfo];
  616. NSLog(@"userInfo: %@", userInfo);
  617. } else if ([response.actionIdentifier isEqualToString:@"customActionIdentifier"]) {
  618. // 处理自定义动作(如果有的话)
  619. }
  620. completionHandler(); // 调用完成处理程序以结束操作
  621. }
  622. - (void)handleNotification:(NSDictionary *)userInfo {
  623. NSDictionary * tempDict = userInfo[@"imMsg"];
  624. NSDictionary * imMsg = tempDict[@"message"];
  625. _isNotification=true;
  626. NSMutableDictionary * mutablemsg = imMsg.mutableCopy;
  627. NSLog(@"------mutablemsg:%@",mutablemsg);
  628. NSDictionary * user = [UDManager.shareInstance getDDManager:dkuserinfo];
  629. if([user[@"id"] isEqual:imMsg[@"fromId"]]){
  630. [mutablemsg setObject:@"true" forKey:@"mine"];
  631. }else{
  632. if([Friendchat isEqual:imMsg[@"type"]]){
  633. [mutablemsg setObject:imMsg[@"fromId"] forKey:@"chatId"];
  634. }
  635. }
  636. if (imMsg) {
  637. if (![LoginStateManager sharedManager].isLoggedIn) {
  638. return;
  639. }
  640. if ([imMsg jk_hasKey:@"addFriend"]) {
  641. return;
  642. }
  643. NSString *strtype = mutablemsg[@"type"];
  644. NSInteger type = [strtype integerValue];
  645. NSString *chatId = mutablemsg[@"chatId"];
  646. NSString *titlename = mutablemsg[@"fromName"]?:@"";
  647. NSString *avatar = mutablemsg[@"fromAvatar"]?:@"";
  648. // NSLog(@"top className:%@",[[self.window jk_topMostController] class]);
  649. // NSLog(@"current className:%@",[[self.window jk_currentViewController] class]);
  650. if ([[self.window jk_currentViewController] isKindOfClass:ChatController.class]) {
  651. ChatController * currentChatVc = (ChatController *)[self.window jk_currentViewController];
  652. if (![currentChatVc.chatId isEqualToString:mutablemsg[@"chatId"]]) {
  653. currentChatVc.chatId = chatId;
  654. currentChatVc.type = type;
  655. currentChatVc.titlename = titlename;
  656. currentChatVc.avatar = avatar;
  657. [currentChatVc reloadAllData];
  658. return;
  659. }
  660. else{
  661. currentChatVc.chatId = chatId;
  662. currentChatVc.type = type;
  663. currentChatVc.titlename = titlename;
  664. currentChatVc.avatar = avatar;
  665. [currentChatVc reloadAllData];
  666. return;
  667. }
  668. }
  669. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  670. ChatController *chatctr = [board instantiateViewControllerWithIdentifier:@"ChatController"];
  671. UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
  672. uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  673. chatctr.chatId = chatId;
  674. chatctr.type = type;
  675. chatctr.titlename = titlename;
  676. chatctr.avatar = avatar;
  677. UITabBarController * tabbarVc = (UITabBarController *)self.window.rootViewController;
  678. ChatIndexController * chatListVc = tabbarVc.viewControllers[0];
  679. if (chatListVc) {
  680. [chatListVc presentViewController:uiNavC animated:YES completion:nil];
  681. }
  682. }
  683. }
  684. #pragma mark -user state and note
  685. -(void)onLoginSucc{
  686. self.isLogin =TRUE;
  687. [self openFMDB];
  688. [self openMainController];
  689. [self updivicetoken];
  690. [self updiviceVoIPtoken];
  691. [self sartWebsocket];
  692. }
  693. -(void)onLogoutSucc{
  694. self.isLogin =false;
  695. NSLog(@"1-----------------1");
  696. // [GDBManager.shareInstance delLocalmsglistTable:userid];
  697. // [GDBManager.shareInstance delchatlistTable:nil fail:nil];
  698. // [GDBManager.shareInstance deleteDB];
  699. [UDManager.shareInstance removeUDManager:gkeytoken];
  700. [UDManager.shareInstance removeUDManager:dkuserloginId];
  701. [UDManager.shareInstance removeUDManager:dkuserinfo];
  702. [UDManager.shareInstance removeUDManager:dkuserId];
  703. [self clearVoipToken];
  704. [self openLoginController];
  705. [self endWebsocket];
  706. [self resetBadgeCount];
  707. [self resetAddFriendBadgeCount];
  708. }
  709. -(void)clearVoipToken{
  710. NSString *voiptoken = [UDManager.shareInstance getSDManager:dkvoiptoken];
  711. NSLog(@"voiptoken:%@",voiptoken);
  712. if([voiptoken isKindOfClass:[NSString class]]&&voiptoken.length>10){
  713. NSDictionary *dic = @{
  714. @"voipTk":voiptoken
  715. };
  716. [UserNetApi clearVoipTk:dic succ:^(int code, NSDictionary * res) {
  717. NSLog(@"clearVoipTk:%@",res);
  718. self->_isTokenCleared=YES;
  719. } fail:^(NSError * _Nonnull error) {
  720. }];
  721. }
  722. NSString *pushtoken = [UDManager.shareInstance getSDManager:dkpushtoken];
  723. NSLog(@"voiptoken:%@",pushtoken);
  724. if([pushtoken isKindOfClass:[NSString class]]&&pushtoken.length>10){
  725. NSDictionary *dic = @{
  726. @"registrationId":pushtoken
  727. };
  728. [UserNetApi clearRegistrationId:dic succ:^(int code, NSDictionary * res) {
  729. NSLog(@"clearRegistrationId:%@",res);
  730. self->_isTokenCleared=YES;
  731. } fail:^(NSError * _Nonnull error) {
  732. }];
  733. }
  734. }
  735. #pragma mark mainControllor Manager
  736. -(void)openMainController{
  737. NSLog(@"openMainController");
  738. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  739. UITabBarController *tbc = [board instantiateViewControllerWithIdentifier:@"GTabBarController"];
  740. //UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tbc];
  741. NSArray *ctrs = tbc.viewControllers;
  742. //------------1
  743. UIViewController *time = ctrs[0];
  744. // 创建一个新的 UITabBarItem
  745. UIImage *index = [[UIImage imageNamed:@"index"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  746. UIImage *index_cur = [[UIImage imageNamed:@"index_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  747. UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem1", @"")
  748. image:index
  749. selectedImage:index_cur];
  750. // 设置标签文本
  751. tabBarItem.title = NSLocalizedString(@"TabBarItem1", @"");
  752. // 设置标签的文本颜色
  753. [tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  754. [tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  755. [time setTabBarItem:tabBarItem];
  756. //----------------2
  757. time = ctrs[1];
  758. // 创建一个新的 UITabBarItem
  759. UIImage *index1 = [[UIImage imageNamed:@"txl"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  760. UIImage *index_cur1 = [[UIImage imageNamed:@"txl_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  761. UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem2", @"")
  762. image:index1
  763. selectedImage:index_cur1];
  764. // 设置标签文本
  765. tabBarItem1.title = NSLocalizedString(@"TabBarItem2", @"");
  766. // 设置标签的文本颜色
  767. [tabBarItem1 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  768. [tabBarItem1 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  769. [time setTabBarItem:tabBarItem1];
  770. //------------------3
  771. time = ctrs[2];
  772. // 创建一个新的 UITabBarItem
  773. UIImage *index2 = [[UIImage imageNamed:@"qunzu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  774. UIImage *index_cur2 = [[UIImage imageNamed:@"qunzu_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  775. UITabBarItem *tabBarItem2 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem3", @"")
  776. image:index2
  777. selectedImage:index_cur2];
  778. // 设置标签文本
  779. tabBarItem2.title = NSLocalizedString(@"TabBarItem3", @"");
  780. // 设置标签的文本颜色
  781. [tabBarItem2 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  782. [tabBarItem2 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  783. [time setTabBarItem:tabBarItem2];
  784. //------------------4
  785. time = ctrs[3];
  786. // 创建一个新的 UITabBarItem
  787. UIImage *index3 = [[UIImage imageNamed:@"wode"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  788. UIImage *index_cur3 = [[UIImage imageNamed:@"wode_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  789. UITabBarItem *tabBarItem3 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem4", @"")
  790. image:index3
  791. selectedImage:index_cur3];
  792. // 设置标签文本
  793. tabBarItem3.title = NSLocalizedString(@"TabBarItem4", @"");
  794. // 设置标签的文本颜色
  795. [tabBarItem3 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  796. [tabBarItem3 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  797. [time setTabBarItem:tabBarItem3];
  798. self.window.rootViewController = tbc;
  799. }
  800. -(void)openLoginController{
  801. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  802. GLoginController *login = [board instantiateViewControllerWithIdentifier:@"LoginController"];
  803. UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
  804. self.window.rootViewController = nav;
  805. }
  806. #pragma mark openSocket
  807. -(void)sartWebsocket{
  808. NSLog(@"----------------sartWebsocket");
  809. [[GWebSocket shareInstance] connectWebSocket];
  810. }
  811. -(void)endWebsocket{
  812. [[GWebSocket shareInstance] closeWebSocket];
  813. }
  814. #pragma mark init DB
  815. -(void)openFMDB{
  816. [GDBManager.shareInstance createDatabase:^(NSArray * _Nullable array) {
  817. [GDBManager.shareInstance createLocalMSGtable:^(NSArray * _Nullable array) {
  818. } fail:^(NSString * _Nullable error) {
  819. }];
  820. [GDBManager.shareInstance createChattable:^(NSArray * _Nullable array) {
  821. } fail:^(NSString * _Nullable error) {
  822. }];
  823. [GDBManager.shareInstance createLastreadtimetable:^(NSArray * _Nullable array) {
  824. } fail:^(NSString * _Nullable error) {
  825. }];
  826. } fail:^(NSString * _Nullable error) {
  827. }];
  828. }
  829. #pragma mark - UISceneSession lifecycle
  830. //- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
  831. // // Called when a new scene session is being created.
  832. // // Use this method to select a configuration to create the new scene with.
  833. // return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
  834. //}
  835. //
  836. //
  837. //- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
  838. // // Called when the user discards a scene session.
  839. // // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  840. // // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  841. //}
  842. #pragma mark - Core Data stack
  843. @synthesize persistentContainer = _persistentContainer;
  844. - (NSPersistentContainer *)persistentContainer {
  845. // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
  846. @synchronized (self) {
  847. if (_persistentContainer == nil) {
  848. _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"555IM"];
  849. [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
  850. if (error != nil) {
  851. // Replace this implementation with code to handle the error appropriately.
  852. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  853. /*
  854. Typical reasons for an error here include:
  855. * The parent directory does not exist, cannot be created, or disallows writing.
  856. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  857. * The device is out of space.
  858. * The store could not be migrated to the current model version.
  859. Check the error message to determine what the actual problem was.
  860. */
  861. NSLog(@"Unresolved error %@, %@", error, error.userInfo);
  862. abort();
  863. }
  864. }];
  865. }
  866. }
  867. return _persistentContainer;
  868. }
  869. #pragma mark - Core Data Saving support
  870. - (void)saveContext {
  871. NSManagedObjectContext *context = self.persistentContainer.viewContext;
  872. NSError *error = nil;
  873. if ([context hasChanges] && ![context save:&error]) {
  874. // Replace this implementation with code to handle the error appropriately.
  875. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
  876. NSLog(@"Unresolved error %@, %@", error, error.userInfo);
  877. abort();
  878. }
  879. }
  880. #pragma mark 检测网络状态
  881. -(void)startNetworkReachability {
  882. AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
  883. __weak typeof(manager) weakManager = manager;
  884. [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  885. BOOL isReachable = weakManager.isReachable;
  886. self->_isReachable = isReachable;
  887. NSLog(@"startNetworkReachability: %d", isReachable);
  888. if (isReachable) {
  889. } else {
  890. }
  891. }];
  892. [manager startMonitoring];
  893. }
  894. - (BOOL)isReachable {
  895. return _isReachable;
  896. }
  897. #pragma mark applock
  898. - (void)showLockScreen {
  899. // 确保在主线程执行
  900. if (self.shouldShowLock && [[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  901. NSLog(@"showLockScreen--------------1");
  902. if (self.isJitsiMeet) {
  903. [_floatWindow viewInFload:0];
  904. return;
  905. }
  906. else{
  907. [_floatWindow show:1];
  908. }
  909. return;
  910. }
  911. if (!self.isJitsiMeet) {
  912. [_floatWindow hide];
  913. }
  914. }
  915. @end