ifish/Ifish/AppDelegate.m

993 lines
36 KiB
Objective-C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// 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 "PushmassageModel.h"
#import "ConnectWifiViewController.h"
#import "UserModel.h"
#import "DeviceModel.h"
#import "DisconnectNetController.h"
//#import "JPUSHService.h"
#import "DownLoadViewController.h"
//#define RONYUN_APPKEY @"pgyu6atqyxxlu"// 融云appkey
#import "ChatroomModel.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 <Bugly/Bugly.h>
#define BUGLY_APPID @"16d2b238e3"
#import "TalkingData.h"
#define TalkingDataAPPID @"351E6F7956CEF7FB6AABAEB64EF9BF18"
#define BMKMAP_APPKEY @"wYcF3YXqeepKfzruExLPn0eS"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "Socketsingleton.h"
#import "CenterViewController.h"
#import <UMCommunitySDK/UMCommunitySDK.h>
#import <UMCommunitySDK/UMComSession.h>
#import <UMSocialCore/UMSocialCore.h>
#define UMCommunity_APPKEY @"569f530fe0f55a3e9a002502"
#define UMCommunity_SECRET @"462384e695d18d287ee46c423c5dce34"
//友盟分享appkey 和社区可通用
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#define UMSocial_APPKEY @"569f530fe0f55a3e9a002502"
//#import <Bugtags/Bugtags.h>
#define BUGTAGS_APPKEY @"a3ecfc992962e493c57fbfc82041ab11"
#define JPUSH_APPKEY_APPSTORE @"d147124018074eb970474e48"
//企业版
#define JPUSH_APPKEY @"d970d5e193cb2a0bbe41653c"
//摄像头部分
#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 <NIMSDK/NIMSDK.h>
#define NIMAPPKEY @"87b0e3315dfc2df08060bcb54246da68"
#import "NTESDataManager.h"
#import "NTESCustomAttachmentDecoder.h"
#define NIMCERNAME_DEVL @"Ifishpushdevelopment"
#define NIMCERNAME_PRO @"Ifishpushproduction"
//#import "NTESLogManager.h"
#import "NTESLoginManager.h"
#import "NTESNotificationCenter.h"
#import "NTESSDKConfig.h"
NSString *NTESNotificationLogout = @"NTESNotificationLogout";
#import "IfishUncaughtExceptionHandler.h"
//阿里百川
#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import "IfishADTimerViewController.h"
@interface AppDelegate ()<BMKGeneralDelegate,NIMLoginManagerDelegate>
@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{
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<AFMultipartFormData> _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] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
//崩溃日志
/* [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];
}*/
//短信验证
[SMSSDK registerApp:SMSSDK_APPKey withSecret:SMSSDK_APPSec];
[SMSSDK enableAppContactFriends:NO];
// 云信IM
_config = [[NTESSDKConfig alloc] init];
[[NIMSDKConfig sharedConfig] setDelegate:_config];
[[NIMSDK sharedSDK] registerWithAppID:NIMAPPKEY
cerName:NIMCERNAME_PRO];
//注入 NIMKit 内容提供者
[[NIMKit sharedKit] setProvider:[NTESDataManager new]];
//需要自定义消息时使用
[NIMCustomObject registerCustomDecoder:[[NTESCustomAttachmentDecoder alloc]init]];
//登陆云信
/**
* 注册APNS
*/
[self registerAPNsYunXin];
[self setupServices];
[self commonInitListenEvents];
/**
* 初始化BugTags
*/
// BugtagsOptions *options = [[BugtagsOptions alloc] init];
// options.trackingCrashes = YES; // 具体可设置的属性请查看 Bugtags.h
// [Bugtags startWithAppKey:BUGTAGS_APPKEY invocationEvent:BTGInvocationEventBubble options:options];
/**
* 点击通知栏推送消息内容处理
*/
// 获取推送消息 islaunchedByNotification 标识用户是否通过点击通知消息进入本应用 即userInfo
NSDictionary* remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
NSLog(@"%@",remoteNotification);
if (remoteNotification) {
_islaunchedByNotification=YES;
launchedByNotification = YES;
}else{
_islaunchedByNotification=NO;
launchedByNotification = NO;
}
/**
* 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];
// NSString*userID=[userDefsult objectForKey:@"userId"];
// NSString*userId=[NSString stringWithFormat:@"%@",userID];
// [JPUSHService setupWithOption:launchOptions appKey:JPUSH_APPKEY_APPSTORE channel:@"Publish channel" apsForProduction:YES];
//
// [JPUSHService setBadge:1];
// [JPUSHService setTags:nil alias:userId callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
/**
* 友盟社区 分享 v6.4.2
*/
[UMCommunitySDK setAppkey:UMCommunity_APPKEY withAppSecret:UMCommunity_SECRET];
[UMComSession openLog:NO];
//设置友盟社会化组件appkey
//打开调试日志
[[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
// 4s 宽高比 0.66 5 6 6p 宽高比 0.56
// 如果是5autoSizeScaleX=1autoSizeScaleY=1
// 如果是6autoSizeScaleX=1.171875autoSizeScaleY=1.17429577
// 如果是6PlusautoSizeScaleX=1.29375autoSizeScaleY=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"];
if (password) {
firstLogIn=NO;
[self loginAnimated:application];
//企业版打开
// dispatch_async(dispatch_get_main_queue(), ^{
// if (_islaunchedByNotification==NO) {
// [self testCurrenVersion];
// }
// });
}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
// 百川平台基础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;
}
#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);
}
#pragma mark - logic 登录云信
- (void)setupServices
{
NSUserDefaults*userDefsult=[NSUserDefaults standardUserDefaults];
NSString *acount = [userDefsult objectForKey:@"userId"];
if (acount) {
//登陆云信 走自动登录
LoginData *data = [[NTESLoginManager sharedManager] currentLoginData];
NSString *account = [data account];
NSString *token = [data token];
//如果有缓存用户名密码推荐使用自动登录
if ([account length] && [token length])
{
//自动登录
//非强制模式
//[[[NIMSDK sharedSDK] loginManager] autoLogin:account
// token:token];
//这里我们使用强制模式 即不考虑安全登录 多设备同帐号登陆
NIMAutoLoginData * LoginData = [[NIMAutoLoginData alloc] init];
LoginData.account = account;
LoginData.token = token;
//强制模式 强制模式下的自动登录,服务器将不检查当前登录设备是否为上一次登录设备,安全性较低。但相对的更加方便,适合 IM 仅作为辅助模块的 App
LoginData.forcedMode = YES;
[[[NIMSDK sharedSDK] loginManager] autoLogin:LoginData];
[[NTESServiceManager sharedManager] start];
}
}
//[[NTESLogManager sharedManager] start];
[[NTESNotificationCenter sharedCenter] start];
}
- (void)commonInitListenEvents
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(logout:)
name:NTESNotificationLogout
object:nil];
[[[NIMSDK sharedSDK] loginManager] addDelegate:self];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[[NIMSDK sharedSDK] loginManager] removeDelegate:self];
}
#pragma mark - 注册APNS
- (void)registerAPNsYunXin
{
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)])
{
UIUserNotificationType types = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
UIRemoteNotificationType types = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
}
}
//jPush 已去
-(void)registerAPNS{
if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 8.0) {
NSLog(@"Version8.0 %f",[[[UIDevice currentDevice] systemVersion] doubleValue]);
[self registerPushForIOS8];
}else if([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0 && [[[UIDevice currentDevice] systemVersion] doubleValue] < 8.0){
NSLog(@"Version7.0 %f",[[[UIDevice currentDevice] systemVersion] doubleValue]);
[self registerNofitication];
}
}
#pragma mark - iOS8以上注册方法
- (void)registerPushForIOS8{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
//Types
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
//Actions
UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
acceptAction.identifier = @"ACCEPT_IDENTIFIER";
acceptAction.title = @"Accept";
acceptAction.activationMode = UIUserNotificationActivationModeForeground;
acceptAction.destructive = NO;
acceptAction.authenticationRequired = NO;
//Categories
UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
inviteCategory.identifier = @"INVITE_CATEGORY";
[inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
[inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
// [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:categories];
#endif
}
#pragma mark - iOS8以下注册方法
- (void) registerNofitication {
// [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
// [JPUSHService registerDeviceToken:deviceToken];
NSString *token =
[[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
withString:@""]
stringByReplacingOccurrencesOfString:@">"
withString:@""]
stringByReplacingOccurrencesOfString:@" "
withString:@""];
NSLog(@"token:%@",token);
//注册成功将deviceToken保存到yoosee摄像头服务器数据库中
NSString *dToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
dToken = [dToken stringByReplacingOccurrencesOfString:@" " withString:@""];
self.token = [NSString stringWithFormat:@"%@",dToken];
// [[NetManager sharedManager] loginWithUserName:@"237807878@qq.com" password:@"lian1030" token: self.token callBack:^(id JSON) {
//
// LoginResult *loginResult = (LoginResult*)JSON;
// //登陆成功返回 LoginResult数据模型 存储
//
// //[UDManager setIsLogin:YES];
// [UDManager setLoginInfo:loginResult];
//
// NSLog(@"%@",JSON);
// [[NetManager sharedManager] getAccountInfo:loginResult.contactId sessionId:loginResult.sessionId callBack:^(id JSN){
//
// AccountResult *accountResult = (AccountResult*)JSN;
// loginResult.email = accountResult.email;
// loginResult.phone = accountResult.phone;
// loginResult.countryCode = accountResult.countryCode;
// [UDManager setLoginInfo:loginResult];
// }];
//
// }];
//云信
[[NIMSDK sharedSDK] updateApnsToken:deviceToken];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
//[JPUSHService resetBadge];
// [JPUSHService handleRemoteNotification:userInfo];
[self showAlertViewWithUserInfo:userInfo];
//存储推送消息
// PushmassageModel*model=[[PushmassageModel alloc] init];
// model.massageType=userInfo[@"msg_type"];
// NSDictionary*apsDic=userInfo[@"aps"];
// NSDictionary*alertDic=apsDic[@"alert"];
// model.massageBody=alertDic[@"body"];
// model.massageTitle=alertDic[@"title"];
// [[IfishDatabaseManager sharedManager] insertModel:model];
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
// [JPUSHService resetBadge];
NSLog(@"userInfo%@",userInfo);
// [JPUSHService handleRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
[[NSNotificationCenter defaultCenter] postNotificationName:@"PresentView" object:nil];
//推送解绑 JPUSH 推送功能已去
//[self showAlertViewWithUserInfo:userInfo];
// if (_islaunchedByNotification) {
// //通知栏进入应用 定位到消息列表 老版本消息列表在tab栏中 已废弃
//
// [[NSNotificationCenter defaultCenter] postNotificationName:@"PresentView" object:nil];
//
//
// }else{
// //用户在使用应用时,弹出提示框 已废弃功能
// [self showAlertViewWithUserInfo:userInfo];
// }
}
/**
* massageType
1.wendu_warn 2.remove_device3.qu_reply 4.offline_push
* 5.remind_water
*/
-(void)showAlertViewWithUserInfo:(NSDictionary*)userInfo{
if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
{
NSDictionary*apsDic=userInfo[@"aps"];
NSDictionary*alertDic=apsDic[@"alert"];
NSString*body=alertDic[@"body"];
NSString*title=alertDic[@"title"];
NSString*massagetype=userInfo[@"msg_type"];
self.massagetype = massagetype;
// NSString*deviceid=apsDic[@"device_id"];
// NSString*deviceName=apsDic[@"device_name"];
NSString* cancelButtontitle=nil;
UserModel *model=[[DataCenter defaultDtacenter]valueForKey:@"UserLogIn"];
if (![model.userSex isEqual:[NSNull null]]) {
if ([model.userSex isEqualToString:@"1"]) {
cancelButtontitle=@"朕知道了";
}else{
cancelButtontitle=@"本宫知道了";
}
}else{
cancelButtontitle=@"朕知道了";
}
_alert = [[UIAlertView alloc] initWithTitle:title
message:body
delegate:self
cancelButtonTitle:cancelButtontitle
otherButtonTitles:nil];
_alert.tag=JPUSHMASSAGE;
[_alert show];
if ([massagetype isEqualToString:@"remove_device"]) {// 删除设备推送
_deletDeviceAlert=[[UIAlertView alloc] initWithTitle:title
message:body
delegate:self
cancelButtonTitle:cancelButtontitle
otherButtonTitles: nil];
_deletDeviceAlert.tag=DELETDEVICE_ALERT;
[_alert show];
formLogIn=NO;
[[Socketsingleton sharedInstance] cutOffSocket];
[IFISHHTTPTOOL ifishLogindismissvc:nil];
}else if ([massagetype isEqualToString:@"app_update"]){//app 版本升级 推送更新
//offline_push
}else if ([massagetype isEqualToString:@"offline_push"]){
//离线推送
_alert = [[UIAlertView alloc] initWithTitle:title
message:body
delegate:self
cancelButtonTitle:cancelButtontitle
otherButtonTitles:nil];
_alert.tag=OFFLINE_PUSH;
[_alert show];
}
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (alertView.tag==JPUSHMASSAGE) {
// 通知弹窗
// IfishMianTabViewController *mianVC=[[IfishMianTabViewController alloc] init];
//
//
// [UIApplication sharedApplication].delegate.window.rootViewController=mianVC;
}else if(alertView.tag==CURRENTVERSIONALERT){
//非强制更新
if ([self.ismustUpdate isEqualToString:@"0"]) {
if (buttonIndex==1) {
[self UpLoadView];
}else{
if (_islaunchedByNotification==NO){//不是点击通知栏弹窗时 点击通知栏取消弹窗不做处理
UIApplication*application=[UIApplication sharedApplication];
[self loginAnimated:application];
}
}
//强制更新
}else{
if (buttonIndex==0) {
[self UpLoadView];
}
}
}else if (alertView.tag==DELETDEVICE_ALERT){
if (buttonIndex==0) {
//无作用转主界面写
}
}
}
-(void)UpLoadView{
//更新下载弹窗
DownLoadViewController *dowloadView=[[DownLoadViewController alloc]init];
UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:dowloadView];
dowloadView.downAddress=self.downloadAddress;
// if (_islaunchedByNotification==YES) {//app已挂起收到通知直接点击通知进入程序 不走版本检测下载地址已写死
// dowloadView.downAddress=@"https://www.ifish7.com/download/ios.html";
// }
dowloadView.fromsetView=NO;
if ([self.ismustUpdate isEqualToString:@"1"]) {
dowloadView.ismust=YES;
}else{
dowloadView.ismust=NO;
}
// self.window.rootViewController=nav;
[self.window.rootViewController presentViewController:nav animated:YES completion:nil];
[nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar.png"] forBarMetrics:UIBarMetricsDefault];
//[[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.downloadAddress]];
}
#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;
[[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.
//极光
//[JPUSHService resetBadge];
//云信
NSInteger count = [[[NIMSDK sharedSDK] conversationManager] allUnreadCount];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:count];
// application.applicationIconBadgeNumber=0;
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] p2pDisconnect];
[app endBackgroundTask:taskID];
}];
if (taskID == UIBackgroundTaskInvalid) {
[[P2PClient sharedClient] p2pDisconnect];
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;
// 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.
}
- (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
{
//return [[P2PClient sharedClient] interfaceOrientationMask];
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);
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
//注意如果同时使用微信支付、支付宝等其他需要改写回调代理的SDK请在if分支下做区分否则会影响 分享、登录的回调
// 新接口写法
if (![[AlibcTradeSDK sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation]) {
// 处理其他app跳转到自己的app
BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
return result;
}
return YES;
}
//同时实现iOS9+的新系统API
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
// 新接口写法
if (![[AlibcTradeSDK sharedInstance] application:app
openURL:url
options:options]) {
//处理其他app跳转到自己的app如果百川处理过会返回YES
BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
return result;
}
return YES;
}
@end