// // AppDelegate.m // Ifish // // Created by imac on 15/9/27. // Copyright © 2015年 imac. All rights reserved. // #import "AppDelegate.h" #import "ViewController.h" #define CURRENTVERSIONALERT 4200 #define DELETDEVICE_ALERT 4230 #define JPUSHMASSAGE 4210 #define OFFLINE_PUSH 4220 #import "RegistViewController.h" #import "AFNetworking.h" #import "IfishDatabaseManager.h" #import "PushmessageModel.h" #import "ConnectWifiViewController.h" #import "UserModel.h" #import "DeviceModel.h" #import "DisconnectNetController.h" //#import "JPUSHService.h" #import "DownLoadViewController.h" #import "WXApi.h" #import "WXApiManager.h" //#define RONYUN_APPKEY @"pgyu6atqyxxlu"// 融云appkey #import "ChatroomModel.h" #import "SVProgressHUD.h" #define GETRONG_TOKEN 4310 #define iPhone6 \ ([UIScreen instancesRespondToSelector:@selector(currentMode)] \ ? CGSizeEqualToSize(CGSizeMake(750, 1334), \ [[UIScreen mainScreen] currentMode].size) \ : NO) #define iPhone6Plus \ ([UIScreen instancesRespondToSelector:@selector(currentMode)] \ ? CGSizeEqualToSize(CGSizeMake(1242, 2208), \ [[UIScreen mainScreen] currentMode].size) \ : NO) #import #define BUGLY_APPID @"c958830c57"//16d2b238e3旧 #import "TalkingData.h" #define TalkingDataAPPID @"351E6F7956CEF7FB6AABAEB64EF9BF18" #define BMKMAP_APPKEY @"wYcF3YXqeepKfzruExLPn0eS" #import "Socketsingleton.h" #import #import #import #import "AppDelegate+AliPushConfig.h" #define UMCommunity_APPKEY @"569f530fe0f55a3e9a002502" #define UMCommunity_SECRET @"462384e695d18d287ee46c423c5dce34" //友盟分享appkey 和社区可通用 #import "UMSocialWechatHandler.h" #import "UMSocialQQHandler.h" #define UMSocial_APPKEY @"569f530fe0f55a3e9a002502" //#import #define BUGTAGS_APPKEY @"a3ecfc992962e493c57fbfc82041ab11" #define JPUSH_APPKEY_APPSTORE @"d147124018074eb970474e48" //企业版 #define JPUSH_APPKEY @"d970d5e193cb2a0bbe41653c" //摄像头部分 //#import #import "P2PClient.h" #import "MPNotificationView.h" #import "NetManager.h" #import "LoginResult.h" #import "MessageDAO.h" #import "UDManager.h" #import "Utils.h" #import "FListManager.h" #import "UDPManager.h" #import "AccountResult.h" #import "ContactDAO.h" #import "IfishMianTabViewController.h" #import "SDWebImageDownloader.h" #import "IfishUncaughtExceptionHandler.h" //阿里百川 #import #import "IfishADTimerViewController.h" #import "AvoidCrash.h" @interface AppDelegate () @property(nonatomic,strong)ICSDrawerController*ics; @property(nonatomic)NSString*downloadAddress; @property(nonatomic,strong)NSString*versionLabel; //@property(nonatomic,strong) UIAlertView * alert; @property(nonatomic,copy)NSString*ismustUpdate; @property(nonatomic) BOOL islaunchedByNotification; @property(nonatomic,strong) NSString*massagetype; //删除绑定弹窗 //@property(nonatomic,strong)UIAlertView* deletDeviceAlert; //@property (nonatomic,strong) NTESSDKConfig *config; @end BOOL launchedByNotification; BOOL firstLogIn;//全局变量 extern BOOL formLogIn; @implementation AppDelegate #pragma mark - 摄像头部分代码 #pragma mark - 返回三种类型的rect,分别是水平、7.0和其他情况 +(CGRect)getScreenSize:(BOOL)isNavigation isHorizontal:(BOOL)isHorizontal{ CGRect rect = [UIScreen mainScreen].bounds; if(isHorizontal){ rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.height, rect.size.width); } if([[[UIDevice currentDevice] systemVersion] floatValue]<7.0){ rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height-20); } return rect; } +(AppDelegate *)sharedDefault{ dispatch_async(dispatch_get_main_queue(), ^{ }); return (AppDelegate *)[UIApplication sharedApplication].delegate; } +(NSString*)getAppVersion{ return [NSString stringWithFormat:APP_VERSION]; } #pragma mark -- 发送崩溃日志 - (void)sendExceptionLogWithData:(NSData *)data path:(NSString *)path { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer.timeoutInterval = 5.0f; //告诉AFN,支持接受 text/xml 的数据 [AFJSONResponseSerializer serializer].acceptableContentTypes = [NSSet setWithObject:@"text/plain"]; NSString *urlString = @"后台地址"; [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) { [formData appendPartWithFileData:data name:@"file" fileName:@"Exception.txt" mimeType:@"txt"]; } success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { // 删除文件 NSFileManager *fileManger = [NSFileManager defaultManager]; [fileManger removeItemAtPath:path error:nil]; } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) { }]; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window.backgroundColor=[UIColor whiteColor]; [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent; //崩溃日志 /* [IfishUncaughtExceptionHandler setDefaultHandler]; // 发送崩溃日志 需要后台接口 暂无 用bugly NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *dataPath = [path stringByAppendingPathComponent:@"Exception.txt"]; NSData *data = [NSData dataWithContentsOfFile:dataPath]; if (data != nil) { [self sendExceptionLogWithData:data path:dataPath]; }*/ #ifdef __OPTIMIZE__ [AvoidCrash becomeEffective]; #endif //短信验证 [SMSSDK registerApp:SMSSDK_APPKey withSecret:SMSSDK_APPSec]; [SMSSDK enableAppContactFriends:NO]; /** * 注册APNS */ [self registerAPNS:application]; //注册阿里推送 [self registerAliPush]; // 点击通知将 App 从关闭状态启动时,将通知打开回执上报 // 计算点击 OpenCount [CloudPushSDK sendNotificationAck:launchOptions]; // 当APP为关闭状态 收到推送通知,点击 图标 会调用该方法 didFinishLaunchingWithOptions: if (launchOptions) { NSLog(@"\n ====== launchOptions: %@",launchOptions); NSDictionary *pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; if (pushNotificationKey) { self.remoteNotification = pushNotificationKey; // 这里定义自己的处理方式 // 如需要代码控制 BadgeNum (icon右上角的数字等操作) //[UIApplication sharedApplication].applicationIconBadgeNumber = 10; } } //自定义弹出框 [self setUpToastView]; /** * 初始化BugTags */ // BugtagsOptions *options = [[BugtagsOptions alloc] init]; // options.trackingCrashes = YES; // 具体可设置的属性请查看 Bugtags.h // [Bugtags startWithAppKey:BUGTAGS_APPKEY invocationEvent:BTGInvocationEventBubble options:options]; /** * 点击通知栏推送消息内容处理 */ // 获取推送消息 islaunchedByNotification 标识用户是否通过点击通知消息进入本应用 即userInfo /** * TalkingData 统计工具 */ [TalkingData sessionStarted:TalkingDataAPPID withChannelId:@"iphone"]; /** * 启动百度地图 */ // BMKMapManager*mapManager=[[BMKMapManager alloc]init]; // BOOL ret=[mapManager start:BMKMAP_APPKEY generalDelegate:self]; // if (!ret) { // NSLog(@"manager start failed!"); // } // // /** * 极光推送 推送消息已去 用云信 */ NSUserDefaults*userDefsult=[NSUserDefaults standardUserDefaults]; /** * 友盟社区 分享 v6.4.2 */ [UMCommunitySDK setAppkey:UMCommunity_APPKEY withAppSecret:UMCommunity_SECRET]; [UMComSession openLog:NO]; //自定义显示框 [self setUpSVProgressHUD]; //设置友盟社会化组件appkey //打开调试日志 // if (DEBUG) { // [[UMSocialManager defaultManager] openLog:YES]; // } //设置友盟appkey [[UMSocialManager defaultManager] setUmSocialAppkey:UMSocial_APPKEY]; //设置微信AppId、appSecret,分享url //设置微信的appKey和appSecret [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wxb3b27d653ec3e3cb" appSecret:@"79d35215d7ef369b927f7cb21a2b8ff6" redirectURL:@"http://mobile.umeng.com/social"]; //http://mobile.umeng.com/social //设置分享到QQ互联的appKey和appSecret // U-Share SDK为了兼容大部分平台命名,统一用appKey和appSecret进行参数设置,而QQ平台仅需将appID作为U-Share的appKey参数传进即可。 [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1105357959" appSecret:nil redirectURL:@"https://mobile.umeng.com/social"]; //http://mobile.umeng.com/social //打开新浪微博的SSO开关,设置新浪微博回调地址,这里必须要和你在新浪微博后台设置的回调地址一致。需要 //设置新浪的appKey和appSecret [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"1240247140" appSecret:@"d5825aae9f4c8552b60e112b42c345f3" redirectURL:@"https://sns.whalecloud.com/sina2/callback"]; //http://sns.whalecloud.com/sina2/callback [WXApi registerApp:@"wxb3b27d653ec3e3cb"]; // 4s 宽高比 0.66 5 6 6p 宽高比 0.56 // 如果是5,autoSizeScaleX=1,autoSizeScaleY=1; // 如果是6,autoSizeScaleX=1.171875,autoSizeScaleY=1.17429577; // 如果是6Plus,autoSizeScaleX=1.29375,autoSizeScaleY=1.2957; AppDelegate*laoutDelegate=(AppDelegate*)[[UIApplication sharedApplication]delegate]; if (kScreenSize.height>480) { laoutDelegate.autoSizeScaleX=kScreenSize.width/320; laoutDelegate.autoSizeScaleY=kScreenSize.height/568; }else{ laoutDelegate.autoSizeScaleX=1.0; laoutDelegate.autoSizeScaleY=1.0; } NSString *password = [userDefsult objectForKey:@"password"]; NSString *isExit = [userDefsult objectForKey:@"isExit"]; NSString *unionId=[userDefsult stringForKey:@"unionId"]; self.isWechatLogin=NO; if ((password||unionId.length)&&![isExit isEqualToString:@"1"]) { firstLogIn=NO; [self loginAnimated:application]; }else{ if ([isExit isEqualToString:@"1"]) { LogInViewController*logVC=[[LogInViewController alloc]init]; UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:logVC]; self.window.rootViewController=nav; [nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"blackbar.png"] forBarMetrics:UIBarMetricsDefault]; }else{ /** * isExit == 0 或 nil */ firstLogIn=YES; RegistViewController*registVC=[[RegistViewController alloc]init]; UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:registVC]; self.window.rootViewController=nav; [nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"blackbar.png"] forBarMetrics:UIBarMetricsDefault]; } } #pragma mark - 摄像头部分代码 ********************************** [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; // 提供网址 供Reachability 测试网络 NSString *remoteHostName = @"www.baidu.com"; [[Reachability reachabilityWithHostName:remoteHostName] startNotifier]; int ap3cid = [[ShakeManager sharedDefault] ApModeGetID]; if (ap3cid != 0) { self.dwApContactID = ap3cid; self.sWifi = [Utils currentWifiSSID]; [[UDPManager sharedDefault] ScanLanDevice]; return YES; } else { self.dwApContactID = 0; self.sWifi = nil; } //self.dwApContactID = 0;在这里默认0 self.dwApContactID = 0; [[UDPManager sharedDefault] ScanLanDevice]; // 百川平台基础SDK初始化,加载并初始化各个业务能力插件 [[AlibcTradeSDK sharedInstance] asyncInitWithSuccess:^{ } failure:^(NSError *error) { NSLog(@"Init failed: %@", error.description); }]; // 开发阶段打开日志开关,方便排查错误信息 //默认调试模式打开日志,release关闭,可以不调用下面的函数 [[AlibcTradeSDK sharedInstance] setDebugLogOpen:YES]; // 设置全局配置,是否强制使用h5 [[AlibcTradeSDK sharedInstance] setIsForceH5:NO]; [self.window makeKeyAndVisible]; /** * 初始化Bugly */ BuglyConfig *config = [[BuglyConfig alloc] init]; config.unexpectedTerminatingDetectionEnable = YES; config.blockMonitorEnable = YES; config.debugMode = YES; config.reportLogLevel = BuglyLogLevelWarn; [Bugly startWithAppId:BUGLY_APPID config:config]; return YES; } //自定义toast提示框 -(void)setUpToastView{ } //初始化提示框 - (void)setUpSVProgressHUD { [SVProgressHUD setMinimumDismissTimeInterval:2]; [SVProgressHUD setBackgroundColor:RGBA(255, 255, 255, 1)]; [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom]; [SVProgressHUD setBorderColor:RGB(234, 234, 234)]; [SVProgressHUD setBorderWidth:ONE_PIXEL_SIZE]; [SVProgressHUD setFont:SYSTEMSIZE(28)]; [SVProgressHUD setCornerRadius:kSizeFrom750(20)]; [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeCustom]; [SVProgressHUD setImageViewSize:CGSizeMake(kSizeFrom750(80), kSizeFrom750(80))]; [SVProgressHUD setBackgroundLayerColor:[[UIColor blackColor] colorWithAlphaComponent:0.4]]; [SVProgressHUD setMinimumSize:CGSizeMake(kSizeFrom750(300), kSizeFrom750(240))]; } #pragma mark - 摄像头部分代码*********************************** -(void)reachabilityChanged:(NSNotification *)note { Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass:[Reachability class]]); self.networkStatus = [curReach currentReachabilityStatus]; NSMutableDictionary *parameter = [NSMutableDictionary dictionaryWithCapacity:0]; [parameter setObject:[NSNumber numberWithInt:self.networkStatus] forKey:@"status"]; [[NSNotificationCenter defaultCenter] postNotificationName:NET_WORK_CHANGE object:self userInfo:parameter]; } - (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias { NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias); } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } #pragma mark 登录 -(void)loginAnimated:(UIApplication*)appliaction{ formLogIn=NO; [IFISHHTTPTOOL ifishLogindismissvc:nil]; } - (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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. NSLog(@"外部打断"); [[Socketsingleton sharedInstance] cutOffSocket];//外部应用打断时断开soket 如电话 下拉系统通知栏 上拉系统通知栏短信查看等 //摄像头后台模式不能截图 self.isGoBack = YES; // [GWNetSingleton sharedClient] [[P2PClient sharedClient] p2pHungUp]; //2.3 版本 点击home 键 就直接挂起 不让app 后台运行 设置Application does not run in background =YES } - (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. if (application.backgroundTimeRemaining > 10) { NSLog(@"ESPAppDelegate: some thread goto background, remained: %f seconds", application.backgroundTimeRemaining); } //设置为假象服务器断开 // UIApplication *app = [UIApplication sharedApplication]; // UIBackgroundTaskIdentifier taskID = 0; // taskID = [app beginBackgroundTaskWithExpirationHandler:^{ // [[P2PClient sharedClient] disconnect]; // [app endBackgroundTask:taskID]; // }]; // // if (taskID == UIBackgroundTaskInvalid) { // [[P2PClient sharedClient] disconnect]; // NSLog(@"Failed to start background task!"); // return; // } self.isGoBack = YES; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ while (self.isGoBack) { DLog(@"run background"); sleep(1.0); } }); } - (void)applicationWillEnterForeground:(UIApplication *)application { [[Socketsingleton sharedInstance] socketConnectHost]; self.isGoBack = NO; [[NSNotificationCenter defaultCenter] postNotificationName:Noti_WillEnterForeground object:nil]; // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. //后台进 //[[NSNotificationCenter defaultCenter] postNotificationName:@"PresentView" object:nil]; } - (void)applicationDidBecomeActive:(UIApplication *)application { // 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. NSLog(@" \n ------ App 在后台运行 点击 icon 激活的APP ------"); if (application.applicationIconBadgeNumber != 0) { // 发起请求获取未读消息的内容 // 点击 icon 从后台进入应用时, 对 badge 的处理 application.applicationIconBadgeNumber = 0; // // 清除导航栏未读的通知 // [_notificationCenter removeAllDeliveredNotifications]; } } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. //NSLog(@"永久挂起 terminate"); } // 禁止横屏 - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { if (self.canFullScreen) { return UIInterfaceOrientationMaskLandscape; }else { return UIInterfaceOrientationMaskPortrait; } return UIInterfaceOrientationMaskPortrait; } -(void)testCurrenVersion{ //检测版本 post 请求 NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary]; NSString*curentVersion=[infoDic objectForKey:@"CFBundleShortVersionString"]; // AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManager manager]; manager.responseSerializer=[AFHTTPResponseSerializer serializer]; manager.requestSerializer.timeoutInterval=20.f;//请求超时设置 [manager POST:kGetNewestVersion parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"result:%@",resultDic[@"result"]); if ([resultDic[@"result"] isEqualToString:@"100"]) { NSDictionary*DataDic=resultDic[@"data"]; NSString*version=DataDic[@"versionCode"]; NSString*downloadAddress=DataDic[@"appAddress"]; NSString*uploadContent=DataDic[@"uploadContent"]; NSString*isMustUpdate=DataDic[@"isMustUpdate"]; self.ismustUpdate=isMustUpdate; self.downloadAddress=downloadAddress; if (![curentVersion isEqualToString:version]) { if ([_ismustUpdate isEqualToString:@"0"]) { UIAlertView*alertVew=[[UIAlertView alloc]initWithTitle:@"检测到新版本" message:uploadContent delegate:self cancelButtonTitle:@"暂不更新" otherButtonTitles:@"立即更新", nil]; alertVew.tag=CURRENTVERSIONALERT; [alertVew show]; }else{ UIAlertView*alertVew=[[UIAlertView alloc]initWithTitle:@"检测到新版本" message:uploadContent delegate:self cancelButtonTitle:nil otherButtonTitles:@"立即更新", nil]; alertVew.tag=CURRENTVERSIONALERT; [alertVew show]; } }else{ UIApplication*application=[UIApplication sharedApplication]; [self loginAnimated:application]; } }else if ([resultDic[@"result"] isEqualToString:@"101"]){ }else if ([resultDic[@"result"] isEqualToString:@"301"]){ }else if ([resultDic[@"result"] isEqualToString:@"302"]){ } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // [self showTitle:@"" messsage:@"网络异常"]; }]; } - (void)onGetPermissionState:(int)iError{ NSLog(@"vonGetPermissionState %d",iError); } //同时实现iOS9+的新系统API -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { // 新接口写法 if (![[AlibcTradeSDK sharedInstance] application:app openURL:url options:options]) { //处理其他app跳转到自己的app,如果百川处理过会返回YES //友盟会消费掉code所以登录时,不给友盟处理 if (self.isWechatLogin) { return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]; } return [[UMSocialManager defaultManager] handleOpenURL:url]; } return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]; } - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]; } - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]; } @end