// // AppDelegate.m // ZhongJingLianMeng // // Created by youke on 2018/11/14. // Copyright © 2018 youke. All rights reserved. // #import "AppDelegate.h" #import "HWTabBarViewController.h" #import "newsDetailVController.h" #import "homePageViewController.h" #import "activityDetailVController.h" //微信SDK头文件 #import "WXApi.h" #import #import #import "ThirdPartyManager.h" #import "XWAlertView.h" @interface AppDelegate () @property(nonatomic,strong)BMKMapManager *mapManager; @property (strong, nonatomic) HttpRequestManger *sessionManager; @property(nonatomic,assign)BOOL isClick; @property(nonatomic,strong)XWAlertView *alertView; @end @implementation AppDelegate - (HttpRequestManger*) sessionManager{ if (!_sessionManager) { _sessionManager = [[HttpRequestManger alloc]init]; } return _sessionManager; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //取token 手机号 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSString *token = [userDefaults objectForKey:@"usertoken"]; [DKGlobal sharedInstance].token = token; NSString *phoneNumber = [userDefaults objectForKey:@"phoneNumber"]; [DKGlobal sharedInstance].phone = phoneNumber; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // 2.设置根控制器 [self.window switchRootViewController]; // 3.显示窗口 [self.window makeKeyAndVisible]; [WXApi registerApp:WEIXIN_APPKEY]; self.mapManager = [[BMKMapManager alloc]init]; BOOL ret = [self.mapManager start:BAIDUMAP_APPKEY generalDelegate:nil]; if (!ret) { NSLog(@"初始化百度地图失败"); } [UMConfigure initWithAppkey:UMeng_APPKEY channel:@"App Store"]; [UMConfigure setLogEnabled:YES];//设置打开日志 //初始化推送 // Push功能配置 UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init]; entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert|UMessageAuthorizationOptionSound; //如果你期望使用交互式(只有iOS 8.0及以上有)的通知,请参考下面注释部分的初始化代码 if (([[[UIDevice currentDevice] systemVersion]intValue]>=8)&&([[[UIDevice currentDevice] systemVersion]intValue]<10)) { UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init]; action1.identifier = @"action1_identifier"; action1.title=@"打开应用"; action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序 UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init]; //第二按钮 action2.identifier = @"action2_identifier"; action2.title=@"忽略"; action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序,在后台处理 action2.authenticationRequired = YES;//需要解锁才能处理,如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略; action2.destructive = YES; UIMutableUserNotificationCategory *actionCategory1 = [[UIMutableUserNotificationCategory alloc] init]; actionCategory1.identifier = @"category1";//这组动作的唯一标示 [actionCategory1 setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)]; NSSet *categories = [NSSet setWithObjects:actionCategory1, nil]; entity.categories=categories; } //如果要在iOS10显示交互式的通知,必须注意实现以下代码 if ([[[UIDevice currentDevice] systemVersion]intValue]>=10) { UNNotificationAction *action1_ios10 = [UNNotificationAction actionWithIdentifier:@"action1_identifier" title:@"打开应用" options:UNNotificationActionOptionForeground]; UNNotificationAction *action2_ios10 = [UNNotificationAction actionWithIdentifier:@"action2_identifier" title:@"忽略" options:UNNotificationActionOptionForeground]; //UNNotificationCategoryOptionNone //UNNotificationCategoryOptionCustomDismissAction 清除通知被触发会走通知的代理方法 //UNNotificationCategoryOptionAllowInCarPlay 适用于行车模式 UNNotificationCategory *category1_ios10 = [UNNotificationCategory categoryWithIdentifier:@"category1" actions:@[action1_ios10,action2_ios10] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; NSSet *categories = [NSSet setWithObjects:category1_ios10, nil]; entity.categories=categories; } [UNUserNotificationCenter currentNotificationCenter].delegate=self; [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { [[NSOperationQueue mainQueue] addOperationWithBlock:^{ [application registerForRemoteNotifications]; }]; }else{ } }]; [self initShareSDK]; self.launchOptionsDic = launchOptions; // Override point for customization after application launch. return YES; } -(void)initShareSDK{ [ShareSDK registerActivePlatforms:@[ @(SSDKPlatformTypeWechat) ] onImport:^(SSDKPlatformType platformType) { switch (platformType) { case SSDKPlatformTypeWechat: [ShareSDKConnector connectWeChat:[WXApi class]]; break; default: break; } } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) { switch (platformType) { case SSDKPlatformTypeWechat: [appInfo SSDKSetupWeChatByAppId:WEIXIN_APPKEY appSecret:WEIXIN_APPSECRET]; break; default: break; } }]; } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ NSLog(@"%@",[[[[deviceToken description ] stringByReplacingOccurrencesOfString: @"<" withString:@"" ] stringByReplacingOccurrencesOfString: @">" withString:@""] stringByReplacingOccurrencesOfString: @"" withString:@"" ]); [UMessage registerDeviceToken: deviceToken]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSDictionary *)userInfo { } // 收到友盟的消息推送 -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{ if (application.applicationState == UIApplicationStateActive) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"title"] message:[[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show]; return; } //如果是在后台挂起,用户点击进入是UIApplicationStateInactive这个状态 else if (application.applicationState == UIApplicationStateInactive){ //...... } // 这个是友盟自带的前台弹出框 [UMessage setAutoAlert:NO]; if([[[UIDevice currentDevice] systemVersion]intValue] < 10){ [UMessage didReceiveRemoteNotification:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } } //iOS10新增:处理前台收到通知的代理方法 -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{ NSDictionary * userInfo = notification.request.content.userInfo; if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { //应用处于前台时的远程推送接受 //关闭U-Push自带的弹出框 [UMessage setAutoAlert:NO]; //必须加这句代码 [UMessage didReceiveRemoteNotification:userInfo]; }else{ //应用处于前台时的本地推送接受 } //当应用处于前台时提示设置,需要哪个可以设置哪一个 completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert); } //iOS10新增:处理后台点击通知的代理方法 -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{ NSDictionary * userInfo = response.notification.request.content.userInfo; if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { #ifdef UM_Swift [UMessageSwiftInterface didReceiveRemoteNotificationWithUserInfo:userInfo]; #else [self jumpToApageWithUserInfo:userInfo]; //应用处于后台时的远程推送接受 //必须加这句代码 [UMessage didReceiveRemoteNotification:userInfo]; #endif }else{ //应用处于后台时的本地推送接受 } } -(void)jumpToApageWithUserInfo:(NSDictionary *)dic{ NSLog(@"%@",dic); HWTabBarViewController *TabVC =(HWTabBarViewController *)[UIApplication sharedApplication].keyWindow.rootViewController; if ([dic[@"status"] isEqualToString:@"1"]) { NSString *typeString = dic[@"jumpType"]; if ([typeString isEqualToString:@"1"] ||[typeString isEqualToString:@"2"]) { newsDetailVController *newsDetail = [[newsDetailVController alloc]init]; newsDetail.typeStr = @"0"; newsDetail.titleStr = dic[@"title"]; newsDetail.shareTitle = dic[@"title"]; newsDetail.index =@"0"; newsDetail.urlStr = [NSString stringWithFormat:@"%@/newsInfo?id=%@&move=ios",baseH5,dic[@"Id"]]; newsDetail.shareUrl = [NSString stringWithFormat:@"%@/newsInfo?id=%@",baseH5,dic[@"Id"]]; newsDetail.newsId = dic[@"Id"]; newsDetail.hidesBottomBarWhenPushed = YES; [TabVC.viewControllers[TabVC.selectedIndex] pushViewController:newsDetail animated:YES]; newsDetail.hidesBottomBarWhenPushed = YES; }else if ([typeString isEqualToString:@"4"]){ newsDetailVController *newsDetail = [[newsDetailVController alloc]init]; newsDetail.newsId = dic[@"Id"]; newsDetail.titleStr = dic[@"title"]; newsDetail.shareTitle = dic[@"title"]; newsDetail.typeStr = @"2"; newsDetail.index =@"0"; newsDetail.urlStr = dic[@"baseUrl"]; newsDetail.shareUrl = dic[@"baseUrl"]; newsDetail.hidesBottomBarWhenPushed = YES; [TabVC.viewControllers[TabVC.selectedIndex] pushViewController:newsDetail animated:YES]; newsDetail.hidesBottomBarWhenPushed = YES; }else if ([typeString isEqualToString:@"3"]){ activityDetailVController *activityDetail = [[activityDetailVController alloc]init]; activityDetail.newsId = dic[@"Id"]; activityDetail.titleStr = dic[@"title"]; activityDetail.shareTitle = dic[@"title"]; activityDetail.activityStatus = dic[@"activity"]; activityDetail.urlStr = [NSString stringWithFormat:@"%@&move=ios",dic[@"baseUrl"]]; activityDetail.shareUrl = [NSString stringWithFormat:@"%@",dic[@"baseUrl"]]; activityDetail.hidesBottomBarWhenPushed = YES; [TabVC.viewControllers[TabVC.selectedIndex] pushViewController:activityDetail animated:YES]; activityDetail.hidesBottomBarWhenPushed = YES; } }else{ UIViewController *vc = self.window.rootViewController; UITabBarController *tvc; tvc = (UITabBarController *)vc; tvc.selectedIndex = 0; } } // iOS9 above - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { if ([url.absoluteString hasPrefix:WEIXIN_APPKEY]) { return [[ThirdPartyManager sharedManager] WXOpenUrl:url]; }else if ([url.host isEqualToString:@"safepay"]) { [[ThirdPartyManager sharedManager] AliPayOpenUrl:url]; } return YES; } // iOS9 below - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { if ([url.absoluteString hasPrefix:WEIXIN_APPKEY]) { return [[ThirdPartyManager sharedManager] WXOpenUrl:url]; }else if ([url.host isEqualToString:@"safepay"]) { [[ThirdPartyManager sharedManager] AliPayOpenUrl:url]; } return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { if (_isClick == NO) { [self checkVersion]; } // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } -(void)checkVersion{ NSMutableDictionary *dic =[NSMutableDictionary dictionary]; dic[@"platform"] = @2; [self.sessionManager sendPostHttpRequestWithUrl:getUpgradeVersionInfo params:dic bodyBlock:nil progress:nil success:^(NSDictionary *response) { NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary]; NSString *currentVersion=infoDic[@"CFBundleShortVersionString"]; NSString *serverVersion = response[@"data"][@"versionName"]; NSString *message = response[@"data"][@"upgradeDesc"]; if ([self compareServerVersion:serverVersion withLocalVersion:currentVersion]){ NSString *str1 = message; _alertView = [[XWAlertView alloc]initWithimage:[UIImage imageNamed:@"huojian"] message:str1 versionId:[NSString stringWithFormat:@"V%@",serverVersion] isForcedUpdating:[NSString stringWithFormat:@"%@",response[@"data"][@"forcedUpdating"]]]; _alertView.resultIndex = ^(NSInteger index) { [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/%E4%B8%AD%E7%BB%8F%E8%81%94%E7%9B%9F%E5%AE%98%E6%96%B9%E6%89%8B%E6%9C%BA%E5%BA%94%E7%94%A8/id1102697591"]]; _isClick = YES; }; [_alertView showAlertView]; } } failure:^(NSError *error) { NSLog(@"%@",error); }]; } - (BOOL)compareServerVersion:(NSString*)serverVersion withLocalVersion:(NSString*)localVersion { BOOL ret =NO; if (serverVersion ==nil || [serverVersion isEqualToString:@""]) { NSLog(@"Server version is empty."); return ret; } if (localVersion ==nil || [localVersion isEqualToString:@""]) { NSLog(@"Local version is empty."); return ret; } NSArray *serComps = [serverVersion componentsSeparatedByString:@"."]; NSArray *locComps = [localVersion componentsSeparatedByString:@"."]; for (int index =0; index < serComps.count; index++) { int numServer = [[serComps objectAtIndex:index] intValue]; int numLocal = -1; if (locComps.count > index) { numLocal = [[locComps objectAtIndex:index]intValue]; } if (numServer > numLocal) { ret =YES; break; }else if (numServer < numLocal) { ret =NO; break; } } return ret; } - (void)dealloc { if (_sessionManager) { [_sessionManager cancelAllTask]; } [[NSNotificationCenter defaultCenter] removeObserver:self]; DebugLog(@"%@没有造成循环引用", [self class]); } @end