AppDelegate.m 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. content.userInfo = @{
  302. @"addFriend":@(1)
  303. };
  304. UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1 repeats:NO];
  305. NSString *identifier = [NSString stringWithFormat:@"FriendRequest_%@", [[NSUUID UUID] UUIDString]];
  306. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
  307. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  308. if (error) {
  309. NSLog(@"发送本地通知失败: %@", error);
  310. } else {
  311. NSLog(@"发送本地通知成功");
  312. }
  313. }];
  314. }
  315. - (void)updateApplicationIconBadgeNumber {
  316. NSInteger total = self.badgeCount + self.addFriendBadgeCount;
  317. if (@available(iOS 16.0, *)) {
  318. [[UNUserNotificationCenter currentNotificationCenter] setBadgeCount:total withCompletionHandler:^(NSError * _Nullable error) {
  319. if (error) {
  320. NSLog(@"设置消息未读数 error: %@", error);
  321. }
  322. }];
  323. } else {
  324. // Fallback on earlier versions
  325. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:total];
  326. }
  327. }
  328. - (void)resetAddFriendBadgeCount {
  329. self.addFriendBadgeCount = 0;
  330. [self updateTabBarBadgeValueAtIndex:1 badgeCount:0];
  331. [self updateApplicationIconBadgeNumber];
  332. }
  333. - (void)resetBadgeCount {
  334. self.badgeCount = 0;
  335. [self updateApplicationIconBadgeNumber];
  336. }
  337. - (void)updateTabBarBadgeValueAtIndex:(NSInteger)index badgeCount:(NSInteger)badgeCount {
  338. UITabBarController * tabbarVc = (UITabBarController *)self.window.rootViewController;
  339. if (![tabbarVc isKindOfClass:[UITabBarController class]]) {
  340. return;
  341. }
  342. if(index < 0 || index >= tabbarVc.tabBar.items.count){
  343. return;
  344. }
  345. UITabBarItem *tabBarItem = tabbarVc.tabBar.items[index];
  346. NSString *badgeValue = badgeCount > 0 ? [NSString stringWithFormat:@"%ld", badgeCount] : nil;
  347. badgeValue = badgeValue.length > 2 ? @"99+" : badgeValue;
  348. tabBarItem.badgeValue = badgeValue;
  349. }
  350. - (void)updateBadgeCount:(NSInteger)badgeCount {
  351. self.badgeCount = badgeCount;
  352. [self updateApplicationIconBadgeNumber];
  353. }
  354. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  355. NSLog(@"Received notification: %@", userInfo);
  356. NSDictionary *temp =userInfo[@"imMsg"];
  357. if(temp){
  358. if ([temp jk_hasKey:@"addFriend"]) {
  359. [self addFriend];
  360. }
  361. NSDictionary *msg =temp[@"message"];
  362. NSString *msgtype=msg[@"msgtype"];
  363. if([msgtype isEqualToString:@"close"]){
  364. if(self.uuid!=nil){
  365. NSString *fromId = self.msg[@"fromId"];
  366. if ( [fromId isEqualToString:msg[@"fromId"]]) {
  367. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  368. self.uuid = nil;
  369. self.msg =nil;
  370. }
  371. }
  372. }
  373. }
  374. // 处理推送消息,例如更新UI或处理数据等
  375. completionHandler(UIBackgroundFetchResultNewData);
  376. }
  377. #pragma mark - PKPushRegistryDelegate
  378. - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type {
  379. // 处理推送凭证更新,例如保存 token 到服务器
  380. NSLog(@"Credentials updated: %@", credentials.token);
  381. NSData *deviceToken = (NSData *)credentials.token;
  382. NSRange range = NSMakeRange(0, 16); // 例如,从索引0开始,获取前10个字节
  383. NSData *subData1 = [deviceToken subdataWithRange:range];
  384. range = NSMakeRange(16, 16);
  385. NSData *subData2 = [deviceToken subdataWithRange:range];
  386. range = NSMakeRange(24, 32);
  387. //NSLog(@"subData1: %@",subData1);
  388. //NSLog(@"subData2: %@",subData2);
  389. NSString *token1=[[subData1 description] substringWithRange:range];
  390. NSString *token2=[[subData2 description] substringWithRange:range];
  391. NSString *token = [NSString stringWithFormat:@"%@%@",token1,token2];
  392. NSLog(@"%@",token);
  393. //将token发送到你的服务器或其他需要的地方
  394. NSString *bgMark = [NSString stringWithFormat:@"voip token:%ld",token.length];
  395. [Bugly reportException:[NSException exceptionWithName:bgMark reason:@"" userInfo:nil]];
  396. [UDManager.shareInstance setSDManager:token key:dkvoiptoken];
  397. if(self.isLogin){
  398. [self updiviceVoIPtoken];
  399. }
  400. }
  401. - (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion{
  402. NSDictionary * temp =payload.dictionaryPayload;
  403. temp =temp[@"business"];
  404. temp=temp[@"incomingCallParams"];
  405. NSString *name =temp[@"localizedCallerName"];
  406. NSLog(@"name:%@",name);
  407. temp =payload.dictionaryPayload;
  408. temp =temp[@"imMsg"];
  409. if(self.uuid!=nil||self.isJitsiMeet){//通知对方正忙,功能需要补上
  410. [self isBUSYNow:temp[@"message"]];
  411. return;
  412. }
  413. self.msg = temp[@"message"];
  414. NSLog(@"self.msg-----:%@",self.msg);
  415. CXCallUpdate * callUpdate = [[CXCallUpdate alloc]init];
  416. callUpdate.supportsGrouping = YES;
  417. callUpdate.supportsDTMF = YES;
  418. callUpdate.hasVideo = YES;
  419. callUpdate.supportsHolding = YES;
  420. [callUpdate setLocalizedCallerName:name];
  421. CXHandle * handle = [[CXHandle alloc]initWithType:CXHandleTypePhoneNumber value:@""];
  422. callUpdate.remoteHandle = handle;
  423. self.uuid = [NSUUID UUID];
  424. [self.callProvider reportNewIncomingCallWithUUID:self.uuid update:callUpdate completion:^(NSError * _Nullable error) {
  425. NSLog(@"%@",error);
  426. }];
  427. completion();
  428. }
  429. -(void)isBUSYNow:(NSDictionary *)msg{
  430. NSDate *now = [NSDate date];
  431. NSTimeInterval trt = [now timeIntervalSince1970];
  432. NSInteger time = trt*1000;
  433. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  434. NSDictionary *callMsg = @{
  435. @"code":SendCode_WEBRTC_DFBUSY,
  436. @"message": @{
  437. @"chatId":msg[@"fromId"],
  438. @"fromId":msg[@"chatId"],
  439. @"type":@"0",
  440. @"messageType":MessageType_DFBUSY,
  441. @"timestamp":strtime,
  442. @"payload":@""
  443. }
  444. };
  445. NSError *error;
  446. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
  447. if (!jsonData) {
  448. NSLog(@"Got an error: %@", error);
  449. } else {
  450. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  451. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  452. [GWebSocket.shareInstance sendMsg:jsonString];
  453. }
  454. }
  455. #pragma mark - CXProviderDelegate Methods
  456. - (void)setupCallProvider {
  457. // 创建配置对象
  458. CXProviderConfiguration *config = [[CXProviderConfiguration alloc] init];
  459. config.supportsVideo = YES; // 是否支持视频通话
  460. config.maximumCallGroups = 1; // 最大通话组数
  461. config.maximumCallsPerCallGroup = 1; // 每个通话组的最大通话数
  462. config.supportedHandleTypes = [[NSSet alloc] initWithObjects:[NSNumber numberWithInt:CXHandleTypeGeneric],[NSNumber numberWithInt:CXHandleTypePhoneNumber], nil];//[NSSet setWithArray:@[CXHandleTypePhoneNumber]]; // 支持的号码类型
  463. config.iconTemplateImageData = UIImagePNGRepresentation([UIImage imageNamed:@"AppIcon"]); // 应用图标
  464. config.ringtoneSound = @"ringtone.aiff"; // 铃声文件(可选)
  465. // 创建CXProvider实例
  466. self.callProvider = [[CXProvider alloc] initWithConfiguration:config];
  467. [self.callProvider setDelegate:self queue:nil];
  468. //self.callRoomMap = [NSMutableDictionary dictionary];
  469. }
  470. - (void)providerDidReset:(CXProvider *)provider {
  471. NSLog(@"Provider reset");
  472. }
  473. - (void)provider:(CXProvider *)provider performStartCallAction:(CXStartCallAction *)action {
  474. // 开始通话的逻辑,如连接服务器等
  475. NSLog(@"performStartCallAction:%@",action);
  476. [action fulfill]; // 当通话开始时调用此方法完成action
  477. }
  478. -(void)provider:(CXProvider *)provider performAnswerCallAction:(CXAnswerCallAction *)action{
  479. [self reciveVoip];
  480. //使用GCD创建一个在3秒后执行的定时器
  481. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  482. NSLog(@"performAnswerCallAction:%@",action);
  483. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
  484. // 应用已经解锁并且在前台
  485. if(self.uuid){
  486. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  487. self.msg = nil;
  488. self.uuid = nil;
  489. }
  490. }
  491. });
  492. }
  493. -(void)provider:(CXProvider *)provider timedOutPerformingAction:(CXAction *)action{
  494. if (!self.uuid) {
  495. return;
  496. }
  497. [self.callProvider reportCallWithUUID:self.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  498. self.msg = nil;
  499. self.uuid = nil;
  500. NSLog(@"timedOutPerformingAction:%@",action);
  501. }
  502. - (void)provider:(CXProvider *)provider performEndCallAction:(CXEndCallAction *)action {
  503. // 挂断电话的逻辑,如断开服务器连接等
  504. NSLog(@"performEndCallAction:%@",action);
  505. NSDate *now = [NSDate date];
  506. NSTimeInterval trt = [now timeIntervalSince1970];
  507. NSInteger time = trt*1000;
  508. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  509. NSDictionary *callMsg = @{
  510. @"code":@"9",
  511. @"message": @{
  512. @"chatId":self.msg[@"fromId"],
  513. @"fromId":self.msg[@"chatId"],
  514. @"type":@"0",
  515. @"msgtype":@"close",
  516. @"timestamp":strtime,
  517. @"payload":self.msg[@"payload"]
  518. }
  519. };
  520. NSError *error;
  521. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:callMsg options:0 error:&error];
  522. if (!jsonData) {
  523. NSLog(@"Got an error: %@", error);
  524. } else {
  525. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  526. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  527. [GWebSocket.shareInstance sendMsg:jsonString];
  528. }
  529. self.uuid = nil;
  530. self.msg =nil;
  531. [action fulfill]; // 当通话结束时调用此方法完成action
  532. }
  533. -(void)reciveVoip{
  534. NSLog(@"reciveVoip-------------1");
  535. if(self.msg){
  536. NSNumber *conetType = self.msg[@"conetType"];
  537. NSLog(@"vidio:%@",self.msg[@"payload"]);
  538. BOOL audioOnly = YES;
  539. if(conetType.boolValue){
  540. audioOnly = NO;
  541. }
  542. else{
  543. audioOnly = YES;
  544. }
  545. [self startJSCall:self.msg[@"fromId"] room:self.msg[@"payload"] isCaller:NO audioOnly:audioOnly];
  546. }
  547. }
  548. //开启悬浮窗拨打方式
  549. -(void)startJSCall:(NSString *_Nonnull)chatId room:(NSString *_Nonnull)roomId isCaller:(BOOL)isCaller audioOnly:(BOOL)audioOnly{
  550. self.isJitsiMeet = YES;
  551. if(_jsyuyinctr){
  552. _jsyuyinctr.chatId = chatId.copy;
  553. _jsyuyinctr.room = roomId.copy;
  554. _jsyuyinctr.audioOnly = audioOnly;
  555. _jsyuyinctr.isCaller = isCaller;
  556. }
  557. else{
  558. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  559. _jsyuyinctr = [board instantiateViewControllerWithIdentifier:@"JSGController"];
  560. _jsyuyinctr.modalPresentationStyle = UIModalPresentationFullScreen;
  561. _jsyuyinctr.chatId = chatId.copy;
  562. _jsyuyinctr.room = roomId.copy;
  563. _jsyuyinctr.audioOnly = audioOnly;
  564. _jsyuyinctr.isCaller = isCaller;
  565. }
  566. NSLog(@"startJSCall roomId:%@",roomId);
  567. [_floatWindow showView:_jsyuyinctr.view];
  568. [_jsyuyinctr startJitsiMeetCall];
  569. [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
  570. }
  571. -(void)floadinSmWindow:(NSInteger )type{
  572. if(type!=0){
  573. [_floatWindow viewInFload:type];
  574. }
  575. }
  576. +(void)closeVoip{
  577. if(app.uuid!=nil){
  578. [app.callProvider reportCallWithUUID:app.uuid endedAtDate:nil reason:CXCallEndedReasonDeclinedElsewhere];
  579. app.uuid = nil;
  580. app.msg =nil;
  581. }
  582. }
  583. +(void)JitsiMeetState:(BOOL)state{
  584. app.isJitsiMeet=state;
  585. if(!state){
  586. if(app.shouldShowLock){
  587. [app showLockScreen];
  588. }
  589. else{
  590. [app.floatWindow hide];
  591. }
  592. }
  593. }
  594. +(void)unlockAPP{
  595. app.shouldShowLock=NO;
  596. }
  597. +(void)changeFloadViewState:(BOOL)state{
  598. if (state) {
  599. [app.floatWindow hide];
  600. }
  601. else{
  602. if ([[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  603. [app.floatWindow show:1];
  604. }
  605. }
  606. }
  607. #pragma mark 用户点击消息推送或滑动
  608. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  609. NSDictionary *userInfo = notification.request.content.userInfo;
  610. NSInteger addFriend = [[userInfo objectForKey:@"addFriend"] integerValue];
  611. if (addFriend) {
  612. // 添加好友通知在app内也要展示
  613. completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner |
  614. UNNotificationPresentationOptionSound |
  615. UNNotificationPresentationOptionBadge);
  616. }
  617. }
  618. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
  619. // 处理用户对通知的响应(点击、滑动等)
  620. if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {
  621. // 用户点击了通知
  622. NSDictionary *userInfo = response.notification.request.content.userInfo;
  623. [self handleNotification:userInfo];
  624. NSLog(@"userInfo: %@", userInfo);
  625. } else if ([response.actionIdentifier isEqualToString:@"customActionIdentifier"]) {
  626. // 处理自定义动作(如果有的话)
  627. }
  628. completionHandler(); // 调用完成处理程序以结束操作
  629. }
  630. - (void)handleNotification:(NSDictionary *)userInfo {
  631. NSDictionary * tempDict = userInfo[@"imMsg"];
  632. NSDictionary * imMsg = tempDict[@"message"];
  633. _isNotification=true;
  634. NSMutableDictionary * mutablemsg = imMsg.mutableCopy;
  635. NSLog(@"------mutablemsg:%@",mutablemsg);
  636. NSDictionary * user = [UDManager.shareInstance getDDManager:dkuserinfo];
  637. if([user[@"id"] isEqual:imMsg[@"fromId"]]){
  638. [mutablemsg setObject:@"true" forKey:@"mine"];
  639. }else{
  640. if([Friendchat isEqual:imMsg[@"type"]]){
  641. [mutablemsg setObject:imMsg[@"fromId"] forKey:@"chatId"];
  642. }
  643. }
  644. if (imMsg) {
  645. if (![LoginStateManager sharedManager].isLoggedIn) {
  646. return;
  647. }
  648. if ([imMsg jk_hasKey:@"addFriend"]) {
  649. return;
  650. }
  651. NSString *strtype = mutablemsg[@"type"];
  652. NSInteger type = [strtype integerValue];
  653. NSString *chatId = mutablemsg[@"chatId"];
  654. NSString *titlename = mutablemsg[@"fromName"]?:@"";
  655. NSString *avatar = mutablemsg[@"fromAvatar"]?:@"";
  656. // NSLog(@"top className:%@",[[self.window jk_topMostController] class]);
  657. // NSLog(@"current className:%@",[[self.window jk_currentViewController] class]);
  658. if ([[self.window jk_currentViewController] isKindOfClass:ChatController.class]) {
  659. ChatController * currentChatVc = (ChatController *)[self.window jk_currentViewController];
  660. if (![currentChatVc.chatId isEqualToString:mutablemsg[@"chatId"]]) {
  661. currentChatVc.chatId = chatId;
  662. currentChatVc.type = type;
  663. currentChatVc.titlename = titlename;
  664. currentChatVc.avatar = avatar;
  665. [currentChatVc reloadAllData];
  666. return;
  667. }
  668. else{
  669. currentChatVc.chatId = chatId;
  670. currentChatVc.type = type;
  671. currentChatVc.titlename = titlename;
  672. currentChatVc.avatar = avatar;
  673. [currentChatVc reloadAllData];
  674. return;
  675. }
  676. }
  677. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  678. ChatController *chatctr = [board instantiateViewControllerWithIdentifier:@"ChatController"];
  679. UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:chatctr];
  680. uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  681. chatctr.chatId = chatId;
  682. chatctr.type = type;
  683. chatctr.titlename = titlename;
  684. chatctr.avatar = avatar;
  685. UITabBarController * tabbarVc = (UITabBarController *)self.window.rootViewController;
  686. ChatIndexController * chatListVc = tabbarVc.viewControllers[0];
  687. if (chatListVc) {
  688. [chatListVc presentViewController:uiNavC animated:YES completion:nil];
  689. }
  690. }
  691. }
  692. #pragma mark -user state and note
  693. -(void)onLoginSucc{
  694. self.isLogin =TRUE;
  695. [self openFMDB];
  696. [self openMainController];
  697. [self updivicetoken];
  698. [self updiviceVoIPtoken];
  699. [self sartWebsocket];
  700. }
  701. -(void)onLogoutSucc{
  702. self.isLogin =false;
  703. NSLog(@"1-----------------1");
  704. // [GDBManager.shareInstance delLocalmsglistTable:userid];
  705. // [GDBManager.shareInstance delchatlistTable:nil fail:nil];
  706. // [GDBManager.shareInstance deleteDB];
  707. [UDManager.shareInstance removeUDManager:gkeytoken];
  708. [UDManager.shareInstance removeUDManager:dkuserloginId];
  709. [UDManager.shareInstance removeUDManager:dkuserinfo];
  710. [UDManager.shareInstance removeUDManager:dkuserId];
  711. [self clearVoipToken];
  712. [self openLoginController];
  713. [self endWebsocket];
  714. [self resetBadgeCount];
  715. [self resetAddFriendBadgeCount];
  716. }
  717. -(void)clearVoipToken{
  718. NSString *voiptoken = [UDManager.shareInstance getSDManager:dkvoiptoken];
  719. NSLog(@"voiptoken:%@",voiptoken);
  720. if([voiptoken isKindOfClass:[NSString class]]&&voiptoken.length>10){
  721. NSDictionary *dic = @{
  722. @"voipTk":voiptoken
  723. };
  724. [UserNetApi clearVoipTk:dic succ:^(int code, NSDictionary * res) {
  725. NSLog(@"clearVoipTk:%@",res);
  726. self->_isTokenCleared=YES;
  727. } fail:^(NSError * _Nonnull error) {
  728. }];
  729. }
  730. NSString *pushtoken = [UDManager.shareInstance getSDManager:dkpushtoken];
  731. NSLog(@"voiptoken:%@",pushtoken);
  732. if([pushtoken isKindOfClass:[NSString class]]&&pushtoken.length>10){
  733. NSDictionary *dic = @{
  734. @"registrationId":pushtoken
  735. };
  736. [UserNetApi clearRegistrationId:dic succ:^(int code, NSDictionary * res) {
  737. NSLog(@"clearRegistrationId:%@",res);
  738. self->_isTokenCleared=YES;
  739. } fail:^(NSError * _Nonnull error) {
  740. }];
  741. }
  742. }
  743. #pragma mark mainControllor Manager
  744. -(void)openMainController{
  745. NSLog(@"openMainController");
  746. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  747. UITabBarController *tbc = [board instantiateViewControllerWithIdentifier:@"GTabBarController"];
  748. //UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tbc];
  749. NSArray *ctrs = tbc.viewControllers;
  750. //------------1
  751. UIViewController *time = ctrs[0];
  752. // 创建一个新的 UITabBarItem
  753. UIImage *index = [[UIImage imageNamed:@"index"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  754. UIImage *index_cur = [[UIImage imageNamed:@"index_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  755. UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem1", @"")
  756. image:index
  757. selectedImage:index_cur];
  758. // 设置标签文本
  759. tabBarItem.title = NSLocalizedString(@"TabBarItem1", @"");
  760. // 设置标签的文本颜色
  761. [tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  762. [tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  763. [time setTabBarItem:tabBarItem];
  764. //----------------2
  765. time = ctrs[1];
  766. // 创建一个新的 UITabBarItem
  767. UIImage *index1 = [[UIImage imageNamed:@"txl"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  768. UIImage *index_cur1 = [[UIImage imageNamed:@"txl_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  769. UITabBarItem *tabBarItem1 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem2", @"")
  770. image:index1
  771. selectedImage:index_cur1];
  772. // 设置标签文本
  773. tabBarItem1.title = NSLocalizedString(@"TabBarItem2", @"");
  774. // 设置标签的文本颜色
  775. [tabBarItem1 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  776. [tabBarItem1 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  777. [time setTabBarItem:tabBarItem1];
  778. //------------------3
  779. time = ctrs[2];
  780. // 创建一个新的 UITabBarItem
  781. UIImage *index2 = [[UIImage imageNamed:@"qunzu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  782. UIImage *index_cur2 = [[UIImage imageNamed:@"qunzu_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  783. UITabBarItem *tabBarItem2 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem3", @"")
  784. image:index2
  785. selectedImage:index_cur2];
  786. // 设置标签文本
  787. tabBarItem2.title = NSLocalizedString(@"TabBarItem3", @"");
  788. // 设置标签的文本颜色
  789. [tabBarItem2 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  790. [tabBarItem2 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  791. [time setTabBarItem:tabBarItem2];
  792. //------------------4
  793. time = ctrs[3];
  794. // 创建一个新的 UITabBarItem
  795. UIImage *index3 = [[UIImage imageNamed:@"wode"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  796. UIImage *index_cur3 = [[UIImage imageNamed:@"wode_cur"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  797. UITabBarItem *tabBarItem3 = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"TabBarItem4", @"")
  798. image:index3
  799. selectedImage:index_cur3];
  800. // 设置标签文本
  801. tabBarItem3.title = NSLocalizedString(@"TabBarItem4", @"");
  802. // 设置标签的文本颜色
  803. [tabBarItem3 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateNormal];
  804. [tabBarItem3 setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]} forState:UIControlStateSelected];
  805. [time setTabBarItem:tabBarItem3];
  806. self.window.rootViewController = tbc;
  807. }
  808. -(void)openLoginController{
  809. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  810. GLoginController *login = [board instantiateViewControllerWithIdentifier:@"LoginController"];
  811. UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
  812. self.window.rootViewController = nav;
  813. }
  814. #pragma mark openSocket
  815. -(void)sartWebsocket{
  816. NSLog(@"----------------sartWebsocket");
  817. [[GWebSocket shareInstance] connectWebSocket];
  818. }
  819. -(void)endWebsocket{
  820. [[GWebSocket shareInstance] closeWebSocket];
  821. }
  822. #pragma mark init DB
  823. -(void)openFMDB{
  824. [GDBManager.shareInstance createDatabase:^(NSArray * _Nullable array) {
  825. [GDBManager.shareInstance createLocalMSGtable:^(NSArray * _Nullable array) {
  826. } fail:^(NSString * _Nullable error) {
  827. }];
  828. [GDBManager.shareInstance createChattable:^(NSArray * _Nullable array) {
  829. } fail:^(NSString * _Nullable error) {
  830. }];
  831. [GDBManager.shareInstance createLastreadtimetable:^(NSArray * _Nullable array) {
  832. } fail:^(NSString * _Nullable error) {
  833. }];
  834. } fail:^(NSString * _Nullable error) {
  835. }];
  836. }
  837. #pragma mark - UISceneSession lifecycle
  838. //- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
  839. // // Called when a new scene session is being created.
  840. // // Use this method to select a configuration to create the new scene with.
  841. // return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
  842. //}
  843. //
  844. //
  845. //- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
  846. // // Called when the user discards a scene session.
  847. // // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
  848. // // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
  849. //}
  850. #pragma mark - Core Data stack
  851. @synthesize persistentContainer = _persistentContainer;
  852. - (NSPersistentContainer *)persistentContainer {
  853. // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
  854. @synchronized (self) {
  855. if (_persistentContainer == nil) {
  856. _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"555IM"];
  857. [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
  858. if (error != nil) {
  859. // Replace this implementation with code to handle the error appropriately.
  860. // 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.
  861. /*
  862. Typical reasons for an error here include:
  863. * The parent directory does not exist, cannot be created, or disallows writing.
  864. * The persistent store is not accessible, due to permissions or data protection when the device is locked.
  865. * The device is out of space.
  866. * The store could not be migrated to the current model version.
  867. Check the error message to determine what the actual problem was.
  868. */
  869. NSLog(@"Unresolved error %@, %@", error, error.userInfo);
  870. abort();
  871. }
  872. }];
  873. }
  874. }
  875. return _persistentContainer;
  876. }
  877. #pragma mark - Core Data Saving support
  878. - (void)saveContext {
  879. NSManagedObjectContext *context = self.persistentContainer.viewContext;
  880. NSError *error = nil;
  881. if ([context hasChanges] && ![context save:&error]) {
  882. // Replace this implementation with code to handle the error appropriately.
  883. // 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.
  884. NSLog(@"Unresolved error %@, %@", error, error.userInfo);
  885. abort();
  886. }
  887. }
  888. #pragma mark 检测网络状态
  889. -(void)startNetworkReachability {
  890. AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
  891. __weak typeof(manager) weakManager = manager;
  892. [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  893. BOOL isReachable = weakManager.isReachable;
  894. self->_isReachable = isReachable;
  895. NSLog(@"startNetworkReachability: %d", isReachable);
  896. if (isReachable) {
  897. } else {
  898. }
  899. }];
  900. [manager startMonitoring];
  901. }
  902. - (BOOL)isReachable {
  903. return _isReachable;
  904. }
  905. #pragma mark applock
  906. - (void)showLockScreen {
  907. // 确保在主线程执行
  908. if (self.shouldShowLock && [[APPLocker sharedLocker] isPasswordSet] && [[APPLocker sharedLocker] isLockEnabled]) {
  909. NSLog(@"showLockScreen--------------1");
  910. if (self.isJitsiMeet) {
  911. [_floatWindow viewInFload:0];
  912. return;
  913. }
  914. else{
  915. [_floatWindow show:1];
  916. }
  917. return;
  918. }
  919. if (!self.isJitsiMeet) {
  920. [_floatWindow hide];
  921. }
  922. }
  923. @end