[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/coding/Coding-iOS/master/Coding_iOS/AppDelegate.m [Back]  [Original]

//
//  AppDelegate.m
//  Coding_iOS
//
//  Created by   on 14-7-29.
//  Copyright (c) 2014 Coding. All rights reserved.
//


#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) 
#define _IPHONE80_ 80000

#if DEBUG
#import 
#import "RRFPSBar.h"
#endif

#import "AppDelegate.h"
#import "RootTabViewController.h"
#import "LoginViewController.h"
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "Login.h"
#import "UnReadManager.h"
#import "XGPush.h"
#import "EaseStartView.h"
#import "BaseNavigationController.h"
#import "PasswordViewController.h"
#import "IntroductionViewController.h"
#import "TweetSendViewController.h"
#import "ProjectToChooseListViewController.h"
#import "OTPListViewController.h"
#import "WikiEditViewController.h"

#import "FunctionIntroManager.h"
#import 
#import "Coding_NetAPIManager.h"
#import "EADeviceToServerLog.h"
#import 

#import "Tweet.h"
#import "sys/utsname.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

#pragma mark XGPush
- (void)registerPush{
    UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
    UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                 categories:[NSSet setWithObject:categorys]];
    [[UIApplication sharedApplication] registerUserNotificationSettings:userSettings];
}

#pragma mark UserAgent
- (void)registerUserAgent{
    NSString *userAgent = [NSString userAgentStr];
    NSDictionary *dictionary = @{@"UserAgent" : userAgent};//User-Agent
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
}

#pragma lifeCycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    if (kTarget_Enterprise) {//
        [NSObject preCookieHandle];//cookie 
    }

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    //
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    //sd
    [[[SDWebImageManager sharedManager] imageDownloader] setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
    
    //
    [self customizeInterface];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    
    //UIWebView  User-Agent
    [self registerUserAgent];

    if ([Login isLogin]) {
        [self setupTabViewController];
    }else{
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        [self setupIntroductionViewController];
    }
    [self.window makeKeyAndVisible];
    [FunctionIntroManager showIntroPage];

    if (kTarget_Enterprise) {
        [self completionStartAnimationWithOptions:launchOptions];
    }else{
        EaseStartView *startView = [EaseStartView new];
        @weakify(self);
        [startView startAnimationWithCompletionBlock:^(EaseStartView *easeStartView) {
            @strongify(self);
            [self completionStartAnimationWithOptions:launchOptions];
        }];
    }
    
#if DEBUG
    [[RRFPSBar sharedInstance] setShowsAverage:YES];
    [[RRFPSBar sharedInstance] setHidden:NO];
#endif
    return YES;
}

- (void)completionStartAnimationWithOptions:(NSDictionary *)launchOptions{
    if ([Login isLogin]) {
        NSDictionary *remoteNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (remoteNotification) {
            [BaseViewController handleNotificationInfo:remoteNotification applicationState:UIApplicationStateInactive];
        }
    }
    
    //    UMENG 
    UMConfigInstance.appKey = kUmeng_AppKey;
    [MobClick startWithConfigure:UMConfigInstance];
    
    if (!kTarget_Enterprise) {
        //UMSocialManager & 
        [[UMSocialManager defaultManager] openLog:YES];
        [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
        [[UMSocialManager defaultManager] setUmSocialAppkey:kUmeng_AppKey];
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kSocial_WX_ID appSecret:kSocial_WX_Secret redirectURL:nil];
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:kSocial_QQ_ID  appSecret:kSocial_QQ_Secret redirectURL:nil];
        [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:kSocial_Sina_ID  appSecret:kSocial_Sina_Secret redirectURL:kSocial_Sina_RedirectURL];
        [ENSession setSharedSessionConsumerKey:kSocial_EN_Key consumerSecret:kSocial_EN_Secret optionalHost:nil];
    }
    
    //    
    [XGPush startApp:kXGPush_Id appKey:kXGPush_Key];
    [Login setXGAccountWithCurUser];
    //
    @weakify(self);
    void (^successCallback)(void) = ^(void){
        //
        if([XGPush isUnRegisterStatus] && [Login isLogin]){
            @strongify(self);
            [self registerPush];
        }
    };
    [XGPush initForReregister:successCallback];
    
    //[XGPush registerPush];  //Push
    
    //(app)
    [XGPush handleLaunching:launchOptions];
}

- (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.
    if ([[BaseViewController presentingVC] isKindOfClass:[WikiEditViewController class]]) {
        [(WikiEditViewController *)[BaseViewController presentingVC] saveWikiDraft];
    }
    [[ImageSizeManager shareManager] save];
    [[Tweet tweetForSend] saveSendData];
}

- (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.
}

- (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.
}

- (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.
    if ([Login isLogin]) {
        [[UnReadManager shareManager] updateUnRead];
        UIViewController *presentingVC = [BaseViewController presentingVC];
        SEL selector = NSSelectorFromString(@"refresh");
        if ([presentingVC isKindOfClass:NSClassFromString(@"Message_RootViewController")]
            && [presentingVC respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [presentingVC performSelector:selector];
#pragma clang diagnostic pop
        }
    }
    //    CODING 
    [[EADeviceToServerLog shareManager] tryToStart];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#ifndef Target_Enterprise

// Universal Links - 
#pragma mark Universal Links

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray * __nullable restorableObjects))restorationHandler{
    if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
//        UIViewController *vc = [BaseViewController analyseVCFromLinkStr:userActivity.webpageURL.absoluteString];
//        if (vc) {
//            [BaseViewController presentVC:vc];
//        }
        [BaseViewController presentLinkStr:userActivity.webpageURL.absoluteString];// native  web 
    }else{
        [[UIApplication sharedApplication] openURL:userActivity.webpageURL];
    }
    return YES;
}

#endif

#pragma mark - XGPush Message
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString * deviceTokenStr = [XGPush registerDevice:deviceToken];
    DebugLog(@"deviceTokenStr : %@", deviceTokenStr);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    DebugLog(@"didReceiveRemoteNotification-userInfo:-----\n%@", userInfo);
    [XGPush handleReceiveNotification:userInfo];
    [BaseViewController handleNotificationInfo:userInfo applicationState:[application applicationState]];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    DebugLog(@"%@", error);
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    DebugLog(@"%@", notificationSettings);
    [application registerForRemoteNotifications];
}

#pragma mark - Methods Private
- (void)setupLoginViewController{
#ifdef Target_Enterprise
    
    IntroductionViewController *introductionVC = [[IntroductionViewController alloc] init];
    [self.window setRootViewController:introductionVC];
    [introductionVC presentLoginUI];

#else
    
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    [self.window setRootViewController:[[UINavigationController alloc] initWithRootViewController:loginVC]];
    
#endif
}

- (void)setupIntroductionViewController{
    if (kTarget_Enterprise) {
        IntroductionViewController *introductionVC = [[IntroductionViewController alloc] init];
        [self.window setRootViewController:introductionVC];
    }else{
        [self setupLoginViewController];//
//        IntroductionViewController *introductionVC = [[IntroductionViewController alloc] init];
//        [self.window setRootViewController:introductionVC];
    }
}

- (void)setupTabViewController{
    RootTabViewController *rootVC = [[RootTabViewController alloc] init];
    rootVC.tabBar.translucent = YES;
    
    [self.window setRootViewController:rootVC];
}

- (void)customizeInterface {
    {//UIBarButtonItem &
        NSDictionary *textAttributes = @{
                                         NSFontAttributeName: [UIFont systemFontOfSize:kBackButtonFontSize],
                                         NSForegroundColorAttributeName: kColorLightBlue,
                                         };
        [[UIBarButtonItem appearance] setTitleTextAttributes:textAttributes forState:UIControlStateNormal];
        [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kBackButtonFontSize]} forState:UIControlStateDisabled];
        [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kBackButtonFontSize]} forState:UIControlStateHighlighted];
    }
    //Navtitle
    UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
    [navigationBarAppearance setBackgroundImage:[UIImage imageWithColor:[NSObject baseURLStrIsProduction]? kColorNavBG: kColorActionYellow] forBarMetrics:UIBarMetricsDefault];
    [navigationBarAppearance setTintColor:kColorLightBlue];//
    NSDictionary *textAttributes = @{
                                     NSFontAttributeName: [UIFont systemFontOfSize:kNavTitleFontSize],
                                     NSForegroundColorAttributeName: kColorNavTitle,
                                     };
    [navigationBarAppearance setTitleTextAttributes:textAttributes];
    navigationBarAppearance.backIndicatorImage = [UIImage imageNamed:@"back_green_Nav"];
    navigationBarAppearance.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"back_green_Nav"];

    [[UITextField appearance] setTintColor:kColorLightBlue];//UITextField
    [[UITextView appearance] setTintColor:kColorLightBlue];//UITextView
    [[UISearchBar appearance] setBackgroundImage:[UIImage imageWithColor:kColorTableSectionBg] forBarPosition:0 barMetrics:UIBarMetricsDefault];
}

#pragma mark URL Schemes
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options{
    DebugLog(@"path: %@, params: %@", [url path], [url queryParams]);
    if ([url.absoluteString hasPrefix:kCodingAppScheme]) {
        NSDictionary *queryParams = [url queryParams];
        if ([url.host isEqualToString:@"safepay"]) {//
            [self p_handlePayURL:url];
        }else if (queryParams[@"email"] && queryParams[@"key"]) {//
            [self showPasswordWithURL:url];
        }else if ([queryParams[@"type"] isEqualToString:@"tweet"]){//
            if ([Login isLogin]) {
                [TweetSendViewController presentWithParams:queryParams];
            }else{
                [NSObject showHudTipStr:@""];
            }
        }else{//
            [BaseViewController presentLinkStr:url.absoluteString];
        }
    }else if ([url.scheme isEqualToString:kSocial_WX_ID] && [url.host isEqualToString:@"pay"]){//
        [self p_handlePayURL:url];
    }else if ([url.absoluteString hasPrefix:@"en-:"]){
        return [[ENSession sharedSession] handleOpenURL:url];
    }else{
        return [[UMSocialManager defaultManager] handleOpenURL:url options:options];
    }
    return YES;
}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
//    DebugLog(@"path: %@, params: %@", [url path], [url queryParams]);
//    if ([url.absoluteString hasPrefix:kCodingAppScheme]) {
//        NSDictionary *queryParams = [url queryParams];
//        if ([url.host isEqualToString:@"safepay"]) {//
//            [self p_handlePayURL:url];
//        }else if (queryParams[@"email"] && queryParams[@"key"]) {//
//            [self showPasswordWithURL:url];
//        }else if ([queryParams[@"type"] isEqualToString:@"tweet"]){//
//            if ([Login isLogin]) {
//                [TweetSendViewController presentWithParams:queryParams];
//            }else{
//                [NSObject showHudTipStr:@""];
//            }
//        }else{//
//            [BaseViewController presentLinkStr:url.absoluteString];
//        }
//    }else if ([url.scheme isEqualToString:kSocial_WX_ID] && [url.host isEqualToString:@"pay"]){//
//        [self p_handlePayURL:url];
//    }else if ([url.absoluteString hasPrefix:@"en-:"]){
//        return [[ENSession sharedSession] handleOpenURL:url];
//    }else{
//        return [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
//    }
//    return YES;
//}

- (void)p_handlePayURL:(NSURL *)url{
    UIViewController *vc = [BaseViewController presentingVC];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    if ([vc respondsToSelector:@selector(handlePayURL:)]) {
        [vc performSelector:@selector(handlePayURL:) withObject:url];
    }
#pragma clang diagnostic pop
}

- (BOOL)showPasswordWithURL:(NSURL *)url{
    PasswordType type;
    NSString *email, *key;
    
    if ([[url lastPathComponent] isEqualToString:@"resetPassword"]) {
        type = PasswordReset;
    }else if ([[url lastPathComponent] isEqualToString:@"activate"]){
        type = PasswordActivate;
    }else{
        return NO;
    }
    email = [[url queryParams] objectForKey:@"email"];
    key = [[url queryParams] objectForKey:@"key"];
    if (email.length 

Web Proxy Viewer  |  New URL  |  Original Page