// // AppDelegate.m // smartRhino // // Created by tederen on 2019/10/21. // Copyright © 2019 tederen. All rights reserved. // #import "AppDelegate.h" #import "TabBarController.h" #import "WorkFlowTabbarController.h" #import "WXApi.h" #import "HKFloatManager.h" @interface AppDelegate () @property (nonatomic, strong) TabBarController *tabBar; @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.tabBar = [TabBarController sharedTabBarController]; [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES; [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO]; ///友盟分享 [self configUSharePlatforms]; //初始化环信 [[EaseSDKHelper shareHelper] hyphenateApplication:application appkey:kHuanXinAppKey apnsCertName:kHuanXinApnsName]; // [WXApi registerApp:wxAppKey enableMTA:NO];//不崩溃 [WXApi registerApp:wxAppKey universalLink:@"https://apk.tederen.com"]; [self settingPush: launchOptions]; if (![UserManager checkStringNull:kToken]){ [[EMClient sharedClient] logout:YES completion:^(EMError *aError) { NSData * data = USERDEFAULTSGET(@"USERINFO"); AppUserModel * model = (AppUserModel*) [NSKeyedUnarchiver unarchiveObjectWithData:data]; [[EaseSDKHelper shareHelper] loginEaseWithUsername:model.ImId password:@"123456"]; }]; self.window.rootViewController = self.tabBar; }else{ self.window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; } [self.window makeKeyAndVisible]; [HKFloatManager addFloatVcs:@[@"HKSecondViewController"]]; return YES; } - (void)configUSharePlatforms { [UMConfigure initWithAppkey:UMengAppKey channel:nil]; /* 设置微信的appKey和appSecret */ [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:wxAppKey appSecret:wxAppSecret redirectURL:@"http://mobile.umeng.com/social"]; [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:wxAppKey appSecret:wxAppSecret redirectURL:@"http://mobile.umeng.com/social"]; /* 设置分享到QQ互联的appID * U-Share SDK为了兼容大部分平台命名,统一用appKey和appSecret进行参数设置,而QQ平台仅需将appID作为U-Share的appKey参数传进即可。 */ [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQAppKey/*设置QQ平台的appID*/ appSecret:nil redirectURL:@"http://mobile.umeng.com/social"]; /* 设置新浪的appKey和appSecret */ [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:WBAppKey appSecret:WBAppSecret redirectURL:@"http://mobile.umeng.com/social"]; } - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { NSString * str = [url absoluteString]; if ([str hasPrefix:@"iossmartrhino"]) { if (![UserManager checkStringNull:kToken]){ str = [str substringFromIndex:20]; NSArray *array = [str componentsSeparatedByString:@"&"]; NSDictionary * dict= @{@"Id":array[0],@"type":array[1],@"userId":array[2],@"name":array[3],@"describe":array[4]}; [[NSNotificationCenter defaultCenter] postNotificationName:SHARERETURNSUCCESS object:nil userInfo:dict]; UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [TabBarController sharedTabBarController]; [[TabBarController sharedTabBarController] setSelectedIndex:0]; [window makeKeyAndVisible]; }else{ UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; [window makeKeyAndVisible]; } } return [WXApi handleOpenURL:url delegate:self]; } /// 分享回调 - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { if ([url.host isEqualToString:@"oauth"]){//微信登录 return [WXApi handleOpenURL:url delegate:self]; } //6.3的新的API调用,是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响 NSString * str = [url absoluteString]; if ([str hasPrefix:@"iossmartrhino"]) { if (![UserManager checkStringNull:kToken]){ str = [str substringFromIndex:20]; NSArray *array = [str componentsSeparatedByString:@"&"]; NSDictionary * dict= @{@"Id":array[0],@"type":array[1],@"userId":array[2],@"name":array[3],@"describe":array[4]}; [[NSNotificationCenter defaultCenter] postNotificationName:SHARERETURNSUCCESS object:nil userInfo:dict]; UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [TabBarController sharedTabBarController]; [[TabBarController sharedTabBarController] setSelectedIndex:0]; [window makeKeyAndVisible]; }else{ UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; [window makeKeyAndVisible]; } } BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url options:options]; if (!result) { } return result; } + (UINavigationController *)getRootController { return (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController; } + (UIViewController *)getTopView { UINavigationController *rootNavigation = [self getRootController]; return rootNavigation.topViewController; } + (instancetype)appdelegate { return [UIApplication sharedApplication].delegate; } - (void)applicationWillResignActive:(UIApplication *)application { NSLog(@"applicationWillResignActive"); // [[NSNotificationCenter defaultCenter] postNotificationName:NOTEBOOKSAVE object:nil]; } - (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"applicationDidEnterBackground"); } - (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 { NSLog(@"applicationDidBecomeActive"); } - (void)applicationWillTerminate:(UIApplication *)application { NSLog(@"applicationWillTerminate"); } #pragma mark - 极光 - (void)settingPush:(NSDictionary *)launchOptions { JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init]; entity.types = JPAuthorizationOptionAlert | JPAuthorizationOptionBadge | JPAuthorizationOptionSound; [JPUSHService registerForRemoteNotificationConfig:entity delegate:self]; [JPUSHService setupWithOption:launchOptions appKey:kJGAppKey channel:@"tederen" apsForProduction:YES // 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES. advertisingIdentifier:nil]; [JpushTool setAlias:@"18224073257" completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) { } seq:18224073257]; } // 此方法是必须要有实现,否则SDK将无法处理应用注册的Token,推送也就不会成功 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"%@",deviceToken); [JPUSHService registerDeviceToken:deviceToken]; // [[EaseSDKHelper shareHelper] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { } #pragma mark - JPush // 前台界面收到通知 - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler { // Required NSDictionary * userInfo = notification.request.content.userInfo; if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { [JPUSHService handleRemoteNotification:userInfo]; } completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置 } // 点击通知消息从后台进入前台 willPresentNotification 接收之后会走这个方法 - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { // Required NSDictionary * userInfo = response.notification.request.content.userInfo; if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { [JPUSHService handleRemoteNotification:userInfo]; NSString * message = userInfo[@"aps"][@"alert"]; UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:(UIAlertControllerStyleAlert)]; UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil]; [alert addAction:sureAction]; [UIApplication sharedApplication].applicationIconBadgeNumber = 0; [self.window.rootViewController presentViewController:alert animated:YES completion:nil]; } completionHandler(); // 系统要求执行这个方法 } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // Required, iOS 7 Support [JPUSHService handleRemoteNotification:userInfo]; NSString * message = userInfo[@"aps"][@"alert"]; UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:(UIAlertControllerStyleAlert)]; UIAlertAction * sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil]; [alert addAction:sureAction]; [UIApplication sharedApplication].applicationIconBadgeNumber = 0; [self.window.rootViewController presentViewController:alert animated:YES completion:nil]; completionHandler(UIBackgroundFetchResultNewData); } //#pragma mark 关闭第三方键盘 //- (BOOL)application:(UIApplication*)application shouldAllowExtensionPointIdentifier:(NSString*)extensionPointIdentifier { // if([extensionPointIdentifier isEqualToString:UIApplicationKeyboardExtensionPointIdentifier]) { // return NO; // } // return YES; //} #pragma mark - 微信登录 - (void)onResp:(BaseResp *)resp{ // =============== 获得的微信登录授权回调 ============ if ([resp isMemberOfClass:[SendAuthResp class]]) { NSLog(@"******************获得的微信登录授权******************"); SendAuthResp *aresp = (SendAuthResp *)resp; if (aresp.errCode != 0 ) { dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^{ SHOWERROR(@"微信授权失败"); }); }); return; } //授权成功获取 OpenId NSString *code = aresp.code; [self getWeiXinOpenId:code]; } } - (void)getWeiXinOpenId:(NSString *)code{ /* appid 是 应用唯一标识,在微信开放平台提交应用审核通过后获得 secret 是 应用密钥AppSecret,在微信开放平台提交应用审核通过后获得 code 是 填写第一步获取的code参数 grant_type 是 填authorization_code */ NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",wxAppKey,wxAppSecret,code]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURL *zoneUrl = [NSURL URLWithString:url]; NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil]; NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding]; if (!data1) { dispatch_async(dispatch_get_main_queue(), ^{ SHOWERROR(@"微信授权失败"); }); return ; } // 授权成功,获取token、openID字典 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil]; NSLog(@"token、openID字典===%@",dic); // NSString *access_token = dic[@"access_token"]; // NSString *openid= dic[@"openid"]; if ([dic[@"openid"] length] > 0) { [[NSNotificationCenter defaultCenter] postNotificationName:WeiChatSuccess object:nil userInfo:dic]; }else{ dispatch_async(dispatch_get_main_queue(), ^{ SHOWERROR(@"微信授权失败"); }); return ; } }); } - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray> * _Nullable))restorationHandler { if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) { NSURL *webpageURL = userActivity.webpageURL; NSString * str = [webpageURL absoluteString]; if ([str hasPrefix:@"iossmartrhino"]) { if (![UserManager checkStringNull:kToken]){ str = [str substringFromIndex:20]; NSArray *array = [str componentsSeparatedByString:@"&"]; NSDictionary * dict= @{@"Id":array[0],@"type":array[1],@"userId":array[2],@"name":array[3],@"describe":array[4]}; [[NSNotificationCenter defaultCenter] postNotificationName:SHARERETURNSUCCESS object:nil userInfo:dict]; UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [TabBarController sharedTabBarController]; [[TabBarController sharedTabBarController] setSelectedIndex:0]; [window makeKeyAndVisible]; }else{ UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; [window makeKeyAndVisible]; } } // TODO 根据需求进行处理 } // TODO 根据需求进行处理 return YES; } @end