|
//
// AppDelegate.m
// ThePaperBase
//
// Created by scar1900 on 15/7/15.
// Copyright (c) 2015年 scar1900. All rights reserved.
//
#import "AppDelegate.h"
#import "TPFrontPageController.h"
#import "MLNavigationController.h"
#import "orderController.h"
#import "welcomeAndAdController.h"
#import "operationNavigationController.h"
//for mac
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
//for idfa
#import <AdSupport/AdSupport.h>
#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define _IPHONE80_ 80000
@interface AppDelegate ()<welcomeDelegate,operationNaviDelegate>
@property(nonatomic, strong)welcomeAndAdController *welcomeController;
@property(nonatomic, strong)NSDictionary *launchOptions;
@property(nonatomic, strong)operationNavigationController *operationNaviController;
@end
@implementation AppDelegate
@synthesize enterBackGroundDate;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self integrateShareSDK]; //集成Mob
[self integrateTencentConnect]; //集成qq互联
[self integrateUMengMobClick]; //集成友盟统计
[self integrateAdSame]; //初始化广告SDK
self.launchOptions = launchOptions;
// [self intergrateUMengTrack]; //集成友盟跟踪
NSString *isFirstInto = [TPUserDefault instance].isFirstIntoApp;
NSString *appVersion = [TPUserDefault instance].appVersion;
NSString *currentVersion = [[TPUserDefault instance] getappVer];
NSDictionary * userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo) {
[MobClick event:@"13"];
[UMessage didReceiveRemoteNotification:userInfo];
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
self.window = [[TPWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor blackColor];
self.enterBackGroundDate = nil;
[TPUserDefault instance].isUseSystemFont = @"0";
//处理webview缓存占用过大问题
int cacheSizeMemory = 4*1024*1024; // 4MB
int cacheSizeDisk = 32*1024*1024; // 32MB
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
[CoreDataManager shareInstance]; //初始化数据库
if (!isFirstInto) { //更新启动逻辑(修复帮助页bug及增加清理缓存)
[TPUserDefault instance].appVersion = currentVersion;
[TPUserDefault instance].isFirstIntoApp = @"1";
}else {
if ([appVersion isEqualToString:currentVersion]) {
[self integrateUMengMessage:launchOptions]; //集成友盟推送
[TPUserDefault instance].isFirstIntoApp = @"2";
}else {
[[TPUserDefault instance] clearCache];//解决版本更新数据库闪退(bug fixed:4587)
[TPUserDefault instance].appVersion = currentVersion;
[TPUserDefault instance].isFirstIntoApp = @"1";
}
}
_welcomeController = [[welcomeAndAdController alloc]init];
_welcomeController.remoteUserInfo = userInfo?userInfo:nil;
_welcomeController.delegate = self;
self.window.rootViewController= _welcomeController;
[self.window makeKeyAndVisible];
if ([[TPUserDefault instance].isNightMode intValue] == 1) {
[self.window setMaskAfterOpenNightMode];
}
return YES;
}
- (void)goOutOperateNavigateion {
[self goOutWelcomePage:nil withAdClick:nil];
[self integrateUMengMessage:self.launchOptions]; //集成友盟推送
}
- (void)goOutWelcomePage:(NSDictionary*)userInfo withAdClick:(remotePushBO *)pushBO{
if ([[TPUserDefault instance].isFirstIntoApp intValue] == 1 && !_operationNaviController) {
_operationNaviController = [[operationNavigationController alloc]init];
_operationNaviController.delegate = self;
self.window.rootViewController = _operationNaviController;
[self.window makeKeyAndVisible];
}else {
_operationNaviController = nil;
TPFrontPageController *vc = TPFrontPageController.new;
orderController *leftViewController=[[orderController alloc]init];
//初始化并加载框架页面
_sideViewController=[[YRSideViewController alloc]initWithNibName:nil bundle:nil];
_sideViewController.rootViewController=vc;
_sideViewController.leftViewController=leftViewController;
_sideViewController.rightViewController=nil;
_sideViewController.leftViewShowWidth=1080/2; //设置左侧页面宽度
_sideViewController.needSwipeShowMenu=NO;//默认开启的可滑动展示
_sideViewController.showBoundsShadow = NO; //设置边缘阴影
MLNavigationController *navigationVC = [[MLNavigationController alloc]initWithRootViewController:_sideViewController];
if (isIOS7) {
navigationVC.interactivePopGestureRecognizer.enabled = NO;
}
self.window.rootViewController = navigationVC;
[[TPUserDefault instance] checkMsgMarkStatus];
[self.window makeKeyAndVisible];
if ([[TPUserDefault instance].isNightMode intValue] == 1) {
[self.window setMaskAfterOpenNightMode];
}
_welcomeController = nil;
if (userInfo) { //优先推送
remotePushBO *push= setJsonDicToDataModel(userInfo, [remotePushBO class]);
push.isComeFromRemote = @"1";
[TPUserDefault instance].pushBO = push;
}else {
if (pushBO) {
[TPUserDefault instance].pushBO = pushBO;
}
}
}
}
- (void)integrateShareSDK {
//初始化shareSDK APPKey
@try {
[ShareSDK registerApp:@"6a7bc91d7868"];
}
@catch (NSException *exception) {
}
@finally {
}
/**
* 初始化微信应用
*/
[ShareSDK connectWeChatWithAppId:wechatAppId
appSecret:wechatSecret
wechatCls:[WXApi class]];
//添加新浪微博应用 注册网址 http://open.weibo.com
[ShareSDK connectSinaWeiboWithAppKey:sinaAppId
appSecret:sinaSecret
redirectUri:sinaRedirectUri];
//当使用新浪微博客户端分享的时候需要按照下面的方法来初始化新浪的平台
[ShareSDK connectSinaWeiboWithAppKey:sinaAppId
appSecret:sinaSecret
redirectUri:sinaRedirectUri
weiboSDKCls:[WeiboSDK class]];
// //添加人人网应用 注册网址 http://dev.renren.com
// [ShareSDK connectRenRenWithAppId:renrenAppId
// appKey:renrenAppKey
// appSecret:renrenSecret
// renrenClientClass:[RennClient class]];
//添加豆瓣应用 注册网址
[ShareSDK connectDoubanWithAppKey:doubanAppKey
appSecret:doubanSecret
redirectUri:doubanUri];
/**
* 添加邮件分享
*/
[ShareSDK connectMail];
/**
连接印象笔记应用以使用相关功能,此应用需要引用EverNoteConnection.framework
http://dev.yinxiang.com上注册应用,并将相关信息填写到以下字段
**/
[ShareSDK connectEvernoteWithType:SSEverNoteTypeCN
consumerKey:evernoteConsumerKey
consumerSecret:evernoteSecret];
/**
连接有道云笔记应用以使用相关功能,此应用需要引用YouDaoNoteConnection.framework
http:note.youdao.com/open/developguide.html#app上注册应用,并将相关信息填写到以下字段
**/
[ShareSDK connectYouDaoNoteWithConsumerKey:youdaoConsumerKey
consumerSecret:youdaoSecret
redirectUri:youdaoRedirectUri];
/**
* 连接pocket以及使用相关功能
*/
[ShareSDK connectPocketWithConsumerKey:pocketAppKey redirectUri:pocketRedirectUri];
/**
* 开启复制服务
*/
[ShareSDK connectCopy];
}
- (void)integrateTencentConnect {
[shareUtil connectTecent:QQAppId];
}
- (void)integrateUMengMobClick {
[MobClick setLogEnabled:NO];
[MobClick setCrashReportEnabled:NO];
[MobClick startWithAppkey:UmengMobClickAppKey reportPolicy:BATCH channelId:@"App Store"];
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
[MobClick setAppVersion:version];
}
- (void)intergrateUMengTrack {
NSString * appKey = @"53a91ecd56240bf2e2000682";
NSString * deviceName = [[[UIDevice currentDevice] name] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * mac = [self macString];
NSString * idfa = [self idfaString];
NSString * idfv = [self idfvString];
NSString * urlString = [NSString stringWithFormat:@"http://log.umtrack.com/ping/%@/?devicename=%@&mac=%@&idfa=%@&idfv=%@", appKey, deviceName, mac, idfa, idfv];
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:urlString]] delegate:nil];
}
- (void)integrateUMengMessage:(NSDictionary *)launchOptions{
[UMessage setBadgeClear:NO];
[UMessage startWithAppkey:UmengMessageAppKey launchOptions:launchOptions];
if (isJustIos7) {
UIRemoteNotificationType remoteType = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (remoteType == UIRemoteNotificationTypeNone) {
[self unRegistRemotePushWithIDFA];
}
}else {
if (![[UIApplication sharedApplication] isRegisteredForRemoteNotifications] ) {
[self unRegistRemotePushWithIDFA];
}
}
if (![TPUserDefault instance].isOpenPush || [[TPUserDefault instance].isOpenPush intValue] == 1) {
[self registUmentRemotePush];
}
}
//【需求】IDFA上报优化(bug:5309)
- (void)unRegistRemotePushWithIDFA {
if ([TPUserDefault instance].IDFA) {
NSDictionary *dic = @{@"operateType":@"del",
@"idfa":[TPUserDefault instance].IDFA};
[Remote doJsonAction:2 requestUrl:msgPushAPNsURL parameter:dic delegate:self];
}
}
- (void)integrateAdSame {
[AdsameCubeMaxSDK initWithPublishID:PUBLISH_ID fullscreenId:0 delegate:self];
}
- (void)registUmentRemotePush {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
{
//register remoteNotification types
UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
action1.identifier = @"action1_identifier";
action1.title=@"Accept";
action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init]; //第二按钮
action2.identifier = @"action2_identifier";
action2.title=@"Reject";
action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序,在后台处理
action2.authenticationRequired = YES;//需要解锁才能处理,如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略;
action2.destructive = YES;
UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
categorys.identifier = @"category1";//这组动作的唯一标示
[categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
categories:[NSSet setWithObject:categorys]];
[UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
} else{
//register remoteNotification types
[UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert];
}
#else
//register remoteNotification types
[UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert];
#endif
//for log
[UMessage setLogEnabled:YES];
[UMessage setAutoAlert:NO];
}
- (void)unRegistUmentRemotePush {
[UMessage unregisterForRemoteNotifications];
//注册推送
if ([TPUserDefault instance].umengToken) {
NSDictionary *dic = @{@"token":[TPUserDefault instance].umengToken,
@"operateType":@"del"};
[Remote doJsonAction:1 requestUrl:msgPushAPNsURL parameter:dic delegate:self];
}
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
TPLOG(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
stringByReplacingOccurrencesOfString: @">" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""]);
[TPUserDefault instance].umengToken = [NSString stringWithFormat:@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<"
withString: @""]
stringByReplacingOccurrencesOfString: @">"
withString: @""]
stringByReplacingOccurrencesOfString: @" "
withString: @""]];
//注册推送
if ([TPUserDefault instance].umengToken && [TPUserDefault instance].IDFA) {
NSDictionary *dic = @{@"token":[TPUserDefault instance].umengToken,
@"operateType":@"add",
@"idfa":[TPUserDefault instance].IDFA};
[Remote doJsonAction:0 requestUrl:msgPushAPNsURL parameter:dic delegate:self];
}
if (EnableTokenDisplay == 1) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"获取token成功" message:[TPUserDefault instance].umengToken delegate:nil cancelButtonTitle:@"复制" otherButtonTitles:nil,nil];
alert.delegate = self;
[alert show];
}
[UMessage registerDeviceToken:deviceToken];
[TPUserDefault instance].isRegistedPush = @"1";
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = alertView.message;
ShowMessage(@"复制成功", YES);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSString *str = [NSString stringWithFormat: @"Error: %@", error];
[self unRegistRemotePushWithIDFA];
[TPUserDefault instance].isRegistedPush = @"0";
TPLOG(@"%@", str);
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"获取token失败" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
// alert.delegate = self;
// [alert show];
}
#pragma mark - handler of push method
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
TPLOG(@"=====remote notification info:%@======",userInfo);
[UMessage didReceiveRemoteNotification:userInfo];
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
if([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
[TPUserDefault instance].isEnterFromBackground = @"1";
}else {
[TPUserDefault instance].isEnterFromBackground = @"2";
}
remotePushBO *pushBO = setJsonDicToDataModel(userInfo, [remotePushBO class]);
pushBO.isComeFromRemote = @"1";
[TPUserDefault instance].pushBO = pushBO;
}
//handler of local notification
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notification {
}
- (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.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
self.enterBackGroundDate = [NSDate date];
// 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 inactive state; here you can undo many of the changes made on entering the background.
if (self.enterBackGroundDate) {
NSDate *currentDate = [NSDate date];
long offsetTime = [currentDate timeIntervalSinceDate:self.enterBackGroundDate];
if (offsetTime >= BackgourndRefreshTime) {
[[NSNotificationCenter defaultCenter] postNotificationName:NEEDREFRESHENTERFORGROUND object:nil];
[[TPUserDefault instance] checkMsgMarkStatus];
}
self.enterBackGroundDate = 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.
}
//we chat call back
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
NSString *urlStr = [url absoluteString];
if ([urlStr isMatchedByRegex:@"tencent"]){
return [TencentOAuth HandleOpenURL:url];
}else if ([urlStr isMatchedByRegex:@"QQ"]){
return [QQApiInterface handleOpenURL:url delegate:[shareUtil instance]];
}else {
return [ShareSDK handleOpenURL:url
wxDelegate:self];
}
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
NSString *urlStr = [url absoluteString];
if ([urlStr isMatchedByRegex:@"tencent"]){
return [TencentOAuth HandleOpenURL:url];
}else if ([urlStr isMatchedByRegex:@"QQ"]){
return [QQApiInterface handleOpenURL:url delegate:[shareUtil instance]];
}else {
return [ShareSDK handleOpenURL:url
sourceApplication:sourceApplication
annotation:annotation
wxDelegate:self];
}
}
//#pragma mark - handle memory warning
//- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
// TPLOG(@"Mem warning!!!!!!!!!!!!!!!!!!!!!!");
//}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
self.backgroundSessionCompletionHandler = completionHandler;
TPLOG(@"接受下载完成回调");
}
- (void)remoteResponsSuccess:(int)actionTag withResponsData:(id)responsData {
if (actionTag == 0) {
[TPUserDefault instance].isOpenPush = @"1";
}else if(actionTag == 1){
[TPUserDefault instance].isOpenPush = @"0";
[TPUserDefault instance].umengToken = nil;
}
}
- (void)remoteResponsFailed:(int)actionTag withMessage:(NSString *)message {
ShowTextMessage(message);
}
- (void)startWaitCursor:(int)actionTag {
}
- (void)stopWaitCursor:(int)actionTag {
}
#pragma mark - umeng track
- (NSString * )macString{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
free(buf);
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *macString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return macString;
}
- (NSString *)idfaString {
NSBundle *adSupportBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/AdSupport.framework"];
[adSupportBundle load];
if (adSupportBundle == nil) {
return @"";
}
else{
Class asIdentifierMClass = NSClassFromString(@"ASIdentifierManager");
if(asIdentifierMClass == nil){
return @"";
}
else{
//for no arc
//ASIdentifierManager *asIM = [[[asIdentifierMClass alloc] init] autorelease];
//for arc
ASIdentifierManager *asIM = [[asIdentifierMClass alloc] init];
if (asIM == nil) {
return @"";
}
else{
if(asIM.advertisingTrackingEnabled){
return [asIM.advertisingIdentifier UUIDString];
}
else{
return [asIM.advertisingIdentifier UUIDString];
}
}
}
}
}
- (NSString *)idfvString
{
if([[UIDevice currentDevice] respondsToSelector:@selector( identifierForVendor)]) {
return [[UIDevice currentDevice].identifierForVendor UUIDString];
}
return @"";
}
@end
|