AppDelegate.m 43 KB

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