// // 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" #import "JPUSHService.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 checkDraft]; [self configUSharePlatforms]; //初始化环信 [[EaseSDKHelper shareHelper] hyphenateApplication:application appkey:kHuanXinAppKey apnsCertName:kHuanXinApnsName]; [WXApi registerApp:wxAppKey universalLink:@"https://apk.tederen.com"]; [self settingPush: launchOptions]; WS(weakSelf); if (![UserManager checkStringNull:kToken]){ self.window.rootViewController = weakSelf.tabBar; [[EMClient sharedClient] logout:YES completion:^(EMError *aError) { NSData * data = USERDEFAULTSGET(@"USERINFO"); AppUserModel * model = (AppUserModel*) [NSKeyedUnarchiver unarchiveObjectWithData:data]; [[EMClient sharedClient] loginWithUsername:model.ImId password:@"123456" completion:^(NSString *aUsername, EMError *aError) { EMError *error = aError; dispatch_async(dispatch_get_main_queue(), ^{ if (!error) { //设置是否自动登录 [[EMClient sharedClient].options setIsAutoLogin:YES]; weakSelf.window.rootViewController = weakSelf.tabBar; } else { weakSelf.window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; } }); }]; }]; }else{ self.window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; } [self.window makeKeyAndVisible]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDraft) name:CHECKDRAFT object:nil]; [HKFloatManager addFloatVcs:@[@"HKSecondViewController"]]; return YES; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)configUSharePlatforms { [[UMSocialGlobal shareInstance] setUniversalLinkDic:@{@(UMSocialPlatformType_WechatSession):@"https://apk.tederen.com", @(UMSocialPlatformType_WechatTimeLine):@"https://apk.tederen.com", @(UMSocialPlatformType_QQ):@"https://apk.tederen.com/qq_conn/101901983", @(UMSocialPlatformType_Sina):@"https://apk.tederen.com", }]; [UMConfigure initWithAppkey:UMengAppKey channel:nil]; /* 设置微信的appKey和appSecret */ [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:wxAppKey appSecret:wxAppSecret redirectURL:@"https://apk.tederen.com"]; [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:wxAppKey appSecret:wxAppSecret redirectURL:@"https://apk.tederen.com"]; /* 设置分享到QQ互联的appID * U-Share SDK为了兼容大部分平台命名,统一用appKey和appSecret进行参数设置,而QQ平台仅需将appID作为U-Share的appKey参数传进即可。 */ [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQAppKey/*设置QQ平台的appID*/ appSecret:QQAppSecret redirectURL:@"https://apk.tederen.com"]; /* 设置新浪的appKey和appSecret */ [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:WBAppKey appSecret:WBAppSecret redirectURL:@"https://apk.tederen.com"]; } //- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation //{ // NSString * str = [url absoluteString]; // if ([str hasPrefix:@"iostedeapp"]) { // if (![UserManager checkStringNull:kToken]){ // str = [str substringFromIndex:17]; // NSArray *array = [str componentsSeparatedByString:@"&"]; // NSLog(@"%@",array); // NSDictionary * dict= @{@"Id":array[0],@"type":array[1],@"userId":array[2],@"name":array[3],@"describe":array[4]}; // [self pushVC:dict]; // }else{ // UIWindow *window = [UtilsTools getWindow]; // window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; // [window makeKeyAndVisible]; // } // return YES; // } // return [WXApi handleOpenURL:url delegate:self]; //} /// 分享回调 - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { NSString * str = [url absoluteString]; if ([str hasPrefix:@"iostedeapp"]) { if (![UserManager checkStringNull:kToken]){ str = [str substringFromIndex:17]; NSArray *array = [str componentsSeparatedByString:@"&"]; NSLog(@"%@",array); NSDictionary * dict= @{@"Id":array[0],@"type":array[1],@"userId":array[2],@"name":array[3],@"describe":array[4]}; [self pushVC:dict]; }else{ UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [StoryboardManager shared].login.instantiateInitialViewController; [window makeKeyAndVisible]; } return YES; } return [WXApi handleOpenURL:url delegate:self]; } -(void)pushVC:(NSDictionary *)dict { UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [TabBarController sharedTabBarController]; [[TabBarController sharedTabBarController] setSelectedIndex:0]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:SHARERETURNSUCCESS object:nil userInfo:dict]; }); [window makeKeyAndVisible]; } + (UINavigationController *)getRootController { return (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController; } + (UIViewController *)getTopView { UINavigationController *rootNavigation = [self getRootController]; return rootNavigation.topViewController; } + (instancetype)appdelegate { return (AppDelegate *)[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 { [UIApplication sharedApplication].applicationIconBadgeNumber = 0; [JPUSHService setBadge:0]; } - (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:NO // 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES. advertisingIdentifier:nil]; [JpushTool setAlias:[AppUserModel sharedAppUserModel].Phone completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) { NSLog(@"====%@",iAlias); } seq:[[AppUserModel sharedAppUserModel].Phone integerValue]]; } // 此方法是必须要有实现,否则SDK将无法处理应用注册的Token,推送也就不会成功 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"%@",deviceToken); [JPUSHService registerDeviceToken:deviceToken]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { } #pragma mark- JPUSHRegisterDelegate // iOS 12 Support - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{ NSDictionary * userInfo = notification.request.content.userInfo; if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { [UIApplication sharedApplication].applicationIconBadgeNumber = 0; [JPUSHService setBadge:0]; [self JPushToVC:userInfo[@"data"]]; }else{ //从通知设置界面进入应用 } } // iOS 10 Support - (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 setBadge:0]; } completionHandler(UNNotificationPresentationOptionSound); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置 } // iOS 10 Support - (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]]) { [UIApplication sharedApplication].applicationIconBadgeNumber = 0; [JPUSHService setBadge:0]; [self JPushToVC:userInfo[@"data"]]; } completionHandler(); // 系统要求 } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [JPUSHService handleRemoteNotification:userInfo]; 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 (![[UMSocialManager defaultManager] handleUniversalLink:userActivity options:nil]) { // 其他SDK的回调 } 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; } - (void)checkDraft { id data = USERDEFAULTSGET(DRAFT); if ([data isKindOfClass:[NSDictionary class]]) { NSLog(@"=======%@",data); switch ([data[@"Type"] integerValue]) { case CollectModel_Toipc: { [self submitTopic:data]; } break; case CollectModel_NoteBook: { [self submitNoteBook:data withType:CollectModel_NoteBook]; } break; case CollectModel_NewTopic: { [self submitNoteBook:data withType:CollectModel_NewTopic]; } break; case CollectModel_Notice: { [self submitNotice:data]; } break; case CollectModel_InterMail: { [self submitMail:data]; } break; default: break; } } } - (void)submitTopic:(NSDictionary *)dict { if ([dict[@"GroupId"] integerValue] == 0) { return; } NSMutableDictionary * paraDict = [NSMutableDictionary dictionary]; [paraDict setObject:dict[@"Title"] forKey:@"Title"]; [paraDict setObject:dict[@"UserId"] forKey:@"UserId"]; [paraDict setObject:dict[@"GroupId"] forKey:@"GroupId"]; [paraDict setObject:dict[@"FolderId"] forKey:@"FolderId"]; [paraDict setObject:dict[@"HtmlContent"] forKey:@"HtmlContent"]; [paraDict setObject:dict[@"IsDraft"] forKey:@"IsDraft"]; [paraDict setObject:dict[@"Content"] forKey:@"Content"]; [[HttpManager sharedHttpManager] POSTUrl:Host(APP_Topic_Add) parameters:paraDict responseStyle:JOSN success:^(id _Nonnull responseObject) { NSLog(@"%@",responseObject); NSMutableDictionary * InfoDict = [NSMutableDictionary dictionaryWithDictionary:responseObject[@"Data"]]; NSMutableDictionary * DraftDict = [NSMutableDictionary dictionary]; [DraftDict setObject:dict[@"Type"] forKey:@"Type"]; [DraftDict setObject:InfoDict[@"FolderId"] forKey:@"FolderId"]; [DraftDict setObject:InfoDict[@"GroupId"] forKey:@"GroupId"]; [DraftDict setObject:InfoDict[@"Id"] forKey:@"Id"]; [DraftDict setObject:InfoDict[@"UserId"] forKey:@"UserId"]; [DraftDict setObject:InfoDict[@"UserId"] forKey:@"UserId"]; USERDEFAULTSSET(DraftDict, GROUPTOPICDRAFTINFO); [[NSUserDefaults standardUserDefaults] removeObjectForKey:DRAFT]; } failure:^(NSError * _Nonnull error) { // SHOWERROR([ZYCTool handerResultData:error]) }]; } - (void)submitNoteBook:(NSDictionary *)dict withType:(CollectModelType)type { NSMutableDictionary * paraDict = [NSMutableDictionary dictionary]; [paraDict setObject:dict[@"Title"] forKey:@"Title"]; [paraDict setObject:dict[@"UserId"] forKey:@"UserId"]; [paraDict setObject:dict[@"FolderId"] forKey:@"FolderId"]; [paraDict setObject:dict[@"IsDraft"] forKey:@"IsDraft"]; [paraDict setObject:dict[@"HtmlContent"] forKey:@"HtmlContent"]; [paraDict setObject:dict[@"IsTopic"] forKey:@"IsTopic"]; [paraDict setObject:dict[@"Content"] forKey:@"Content"]; [[HttpManager sharedHttpManager] PUTUrl:Host(API_CreateNoteBook) parameters:paraDict responseStyle:JOSN success:^(id _Nonnull responseObject) { NSLog(@"%@",responseObject); NSMutableDictionary * InfoDict = [NSMutableDictionary dictionaryWithDictionary:responseObject]; [InfoDict setObject:dict[@"Type"] forKey:@"Type"]; USERDEFAULTSSET(InfoDict, type == CollectModel_NoteBook ? NOTEBOOKDRAFTINFO : TOPICBOOKDRAFTINFO); [[NSUserDefaults standardUserDefaults] removeObjectForKey:DRAFT]; } failure:^(NSError * _Nonnull error) { // SHOWERROR([ZYCTool handerResultData:error]); }]; } - (void)submitNotice:(NSDictionary *)dict { NSMutableDictionary * paraDict = [NSMutableDictionary dictionary]; [paraDict setObject:dict[@"Title"] forKey:@"Title"]; [paraDict setObject:dict[@"UserId"] forKey:@"UserId"]; [paraDict setObject:dict[@"NoticeType"] forKey:@"NoticeType"]; [paraDict setObject:dict[@"FolderId"] forKey:@"FolderId"]; [paraDict setObject:dict[@"HtmlContent"] forKey:@"HtmlContent"]; [paraDict setObject:dict[@"TypeValue"] forKey:@"TypeValue"]; [paraDict setObject:dict[@"AddresseeUserMiddles"] forKey:@"AddresseeUserMiddles"]; [paraDict setObject:dict[@"CcUserMiddles"] forKey:@"CcUserMiddles"]; [paraDict setObject:dict[@"Content"] forKey:@"Content"]; [[HttpManager sharedHttpManager] PUTUrl:Host(API_NOTICE_ADD) parameters:paraDict responseStyle:DATA success:^(id _Nonnull responseObject) { NSMutableDictionary * InfoDict = [NSMutableDictionary dictionaryWithDictionary:responseObject]; [InfoDict setObject:dict[@"Type"] forKey:@"Type"]; USERDEFAULTSSET(InfoDict, NOTICERAFTINFO); [[NSUserDefaults standardUserDefaults] removeObjectForKey:DRAFT]; } failure:^(NSError * _Nonnull error) { // SHOWERROR([ZYCTool handerResultData:error]); }]; } - (void)submitMail:(NSDictionary *)dict { NSMutableDictionary * paraDict = [NSMutableDictionary dictionary]; [paraDict setObject:dict[@"Title"] forKey:@"Title"]; [paraDict setObject:dict[@"UserId"] forKey:@"UserId"]; [paraDict setObject:dict[@"FolderId"] forKey:@"FolderId"]; [paraDict setObject:dict[@"HtmlContent"] forKey:@"HtmlContent"]; [paraDict setObject:dict[@"AddresseeUserMiddles"] forKey:@"AddresseeUserMiddles"]; [paraDict setObject:dict[@"CcUserMiddles"] forKey:@"CcUserMiddles"]; [paraDict setObject:dict[@"Content"] forKey:@"Content"]; [paraDict setObject:dict[@"MissiveType"] forKey:@"MissiveType"];///1 正常 2 匿名 [paraDict setObject:dict[@"ParentId"] forKey:@"ParentId"];///回复ID [paraDict setObject:dict[@"TypeValue"] forKey:@"TypeValue"]; [paraDict setObject:dict[@"MissiveAttributeType"] forKey:@"MissiveAttributeType"];///1 发送 2 草稿 [[HttpManager sharedHttpManager] PUTUrl:Host(API_InterLetterModify) parameters:paraDict responseStyle:DATA success:^(id _Nonnull responseObject) { NSMutableDictionary * InfoDict = [NSMutableDictionary dictionaryWithDictionary:responseObject]; [InfoDict setObject:dict[@"Type"] forKey:@"Type"]; USERDEFAULTSSET(InfoDict, MAILRAFTINFO); [[NSUserDefaults standardUserDefaults] removeObjectForKey:DRAFT]; } failure:^(NSError * _Nonnull error) { // SHOWERROR([ZYCTool handerResultData:error]); }]; } - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { // 可以这么写 if (self.allowOrentitaionRotation) { return UIInterfaceOrientationMaskAllButUpsideDown; } return UIInterfaceOrientationMaskPortrait; } #pragma mark - JPushToVC - (void)JPushToVC:(NSDictionary *)dict { UIWindow *window = [UtilsTools getWindow]; window.rootViewController = [TabBarController sharedTabBarController]; if ([dict[@"mediaType"] integerValue] == 10) { [[TabBarController sharedTabBarController] setSelectedIndex:1]; }else{ [[TabBarController sharedTabBarController] setSelectedIndex:0]; } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:JPUSHSUCCESS object:nil userInfo:dict]; }); [window makeKeyAndVisible]; } @end