AppDelegate.m 14.9 KB
//
//  AppDelegate.m
//  IVTMeLiveTwo
//
//  Created by XRG on 16/8/9.
//  Copyright © 2016年 QLQ. All rights reserved.
//

#import "AppDelegate.h"
#import "RootTabBarController.h"
#import "JPUSHService.h"
#import "WeiboSDK.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "GuideView.h"
#import "ADView.h"
#import "UncaughtExceptionHandler.h"
#import "IVTLoginViewController.h"
#import "IVTBindingTelViewController.h"
#import "XMPPManager.h"
#import "AppInfoUtil.h"
#import <CNLiveStat/CNLiveStat.h>

@interface AppDelegate ()<TencentSessionDelegate,WeiboSDKDelegate,WXApiDelegate>
{
}
@end

@implementation AppDelegate

+ (AppDelegate *)appDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (void)quitAndShowLoginView{
    if (self.startPushLiveVC) {
        [self.startPushLiveVC closeForIsShowEndView:NO success:^(BOOL isSuccess) {
            if (isSuccess) {
                [self logOutAndShowLoginView];
            }
        }];
    }
    else{
        [self logOutAndShowLoginView];
    }
}

- (void)logOutAndShowLoginView{
    [IVTAccountTool logOutCurrentUser];
    
    [[XMPPManager sharedInstance] logout];
    
    if (self.livePreviewVC) {
        [self.window.rootViewController dismissViewControllerAnimated:NO completion:nil];
    }
    IVTLoginViewController *loginVC = [[IVTLoginViewController alloc]init];
    [self.window.rootViewController presentViewController:loginVC animated:YES completion:^{
        
    }];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    RootTabBarController *rootTabBarController = [[RootTabBarController alloc]init];
    self.window.rootViewController = rootTabBarController;

    [self.window makeKeyAndVisible];
    
    //极光推送设置
    [self setupJPushWithLaunchOptions:launchOptions];
    //QQ设置
    [self setupQQWithLaunchOptions:launchOptions];
    //sina设置
    [self setupSinaWithLaunchOptions:launchOptions];
    //微信设置
    [self setupWeChatWithLaunchOptions:launchOptions];
//    中国网统计
    [CNLiveStat registerApp:kCNLive_AppID appKey:kCNLive_AppKey];
    
    BOOL isShowedGuide = [[NSUserDefaults standardUserDefaults] boolForKey:kIsShowedGuideLaunchedView];//存储的引导页id
    if (!isShowedGuide) {
        GuideView *guideView = [GuideView sharedInstance];
        [self.window addSubview:guideView];
    }

    InstallUncaughtExceptionHandler();
    
    return YES;
}
/**
 *  极光推送配置,及代理回调
 */
- (void)setupJPushWithLaunchOptions:(NSDictionary *)launchOptions{
    [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
    //0:开发  1:发布
    [JPUSHService setupWithOption:launchOptions appKey:kJPush_AppKey channel:@"0" apsForProduction:YES];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    [JPUSHService handleRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    LRLog(@"error");
}

//获取自定义消息推送内容
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
//    LRLog(@"获取自定义消息推送内容-->%@", userInfo);
    NSString *content = [userInfo valueForKey:@"content"];
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[content dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    content = dict[@"content"];
    
    if (content) {
        [[RootTabBarController tabBarVC] showGlobalMsg:content];
    }
//    content = "{\"title\":\"\U5341\U4e00\U653e\U5047\U901a\U77e5\",\"content\":\"\U996d\U5723\U5927\U975e\U7701\U7684\U65b9\U5f0f\U662f\U5426\U662f\U8bf4\U53d1\U751f\U5927\U5e45\U6536\U8d39\U4e0a\U7684\Uff0c\U65af\U8482\U82ac\U65af\U8482\U82ac\U901f\U5ea6\"}";
//    title = "\U5341\U4e00\U653e\U5047\U901a\U77e5";
    
//    {"title":"十一放假通知","content":"饭圣大非省的方式是否是说发生大幅收费上的,斯蒂芬斯蒂芬速度"}
}

/**
 *  QQ设置
 */
- (void)setupQQWithLaunchOptions:(NSDictionary *)launchOptions{
    _tencentOAuth = [[TencentOAuth alloc]initWithAppId:kQQ_AppID andDelegate:self];
}

#pragma --mark qq授权代理
-(void)tencentDidLogin{
    if (_tencentOAuth.accessToken && [_tencentOAuth.accessToken length] != 0){
        _tencentAccessToken = [_tencentOAuth accessToken];
        _tencentOpenId = [_tencentOAuth openId];
        [self doRegisterOnMyPlatformFrom:kQQType value:_tencentOpenId];
    }
    else{
        LRLog(@"登录不成功");
        
    }
}
- (void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled) {
        LRLog(@"用户取消登录");
    }
    else{
        LRLog(@"登录失败");
    }
}
- (void)tencentDidNotNetWork{
    LRLog(@"无网络连接,请设置网络");
}
/**
 *  新浪设置
 */
- (void)setupSinaWithLaunchOptions:(NSDictionary *)launchOptions{
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:kSina_AppKey];
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class]) {
        WBSendMessageToWeiboResponse *sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse *)response;
        if (sendMessageToWeiboResponse.statusCode == WeiboSDKResponseStatusCodeSuccess) {
            [HUDUtil showSuccess:@"分享成功"];
        } else if (sendMessageToWeiboResponse.statusCode == WeiboSDKResponseStatusCodeUserCancel) {
            [HUDUtil showError:@"分享取消"];
        } else {
            [HUDUtil showError:@"分享失败"];
        }
        NSString *accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken) {
            self.wbAccessToken = accessToken;
        }
        NSString *userId = [sendMessageToWeiboResponse.authResponse userID];
        if (userId) {
            self.wbCurrentUserID = userId;
        }
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class]){
        self.wbAccessToken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
        self.wbRefreshToken = [(WBAuthorizeResponse *)response refreshToken];
        [self doRegisterOnMyPlatformFrom:kSinaType value:_wbCurrentUserID];
    }
    else if([response isKindOfClass:WBShareMessageToContactResponse.class]){
        WBShareMessageToContactResponse *shareMessageToContactResponse = (WBShareMessageToContactResponse *)response;
        NSString *accessToken = [shareMessageToContactResponse.authResponse accessToken];
        if (accessToken) {
            self.wbAccessToken = accessToken;
        }
        NSString *userId = [shareMessageToContactResponse.authResponse userID];
        if (userId) {
            self.wbCurrentUserID = userId;
        }
    }
}
- (void)didReceiveWeiboRequest:(WBBaseRequest *)request{
    
}

/**
 *  微信设置
 */
- (void)setupWeChatWithLaunchOptions:(NSDictionary *)launchOptions{
    [WXApi registerApp:kWX_AppID];
}
- (void)onReq:(BaseReq *)req{
    
}
- (void)onResp:(BaseResp *)resp{
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        if (resp.errCode == WXSuccess) {
            [HUDUtil showSuccess:@"分享成功"];
        }
        else{
            [HUDUtil showError:@"分享失败"];
        }
    }
    else if ([resp isKindOfClass:[SendAuthResp class]]){
        if (resp.errCode == WXSuccess) {
            SendAuthResp *authResp = (SendAuthResp *)resp;
            NSString *code = authResp.code;
            [self getOpenIdAndAccessTokenForWeChatWithCode:code];
        }
    }
    else if ([resp isKindOfClass:[PayResp class]]){
        if (resp.errCode == WXSuccess) {
            [SVProgressHUD setMinimumDismissTimeInterval:2];
            [SVProgressHUD showSuccessWithStatus:@"支付成功"];
        }
        else{
            [SVProgressHUD setMinimumDismissTimeInterval:2];
            [SVProgressHUD showErrorWithStatus:@"支付失败"];
        }
    }
}
- (void)getOpenIdAndAccessTokenForWeChatWithCode:(NSString *)code{
    NSString *urlString = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWX_AppID,kWX_AppSecret,code];
    NSString *dataString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSUTF8StringEncoding error:nil];
    if (dataString) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
        _wxAccessToken  = [dict objectForKey:@"access_token"];
        _wxOpenId = [dict objectForKey:@"openid"];
        _wxRefreshToken = [dict objectForKey:@"refresh_token"];
        
        [self doRegisterOnMyPlatformFrom:kWeChatType value:_wxOpenId];
    }
}

- (void)doRegisterOnMyPlatformFrom:(ThirdPartLoginType)platform value:(NSString *)value{
    [HUDUtil showLoading];
    [[IVTNetworkAPIClient sharedClient] checkIsSuccessedThirdPartLogin:platform value:value success:^(NSDictionary *successData) {
        [HUDUtil hide];
        if ([[successData valueForKey:@"code"] integerValue] == 1) {//没绑定
            [self.window.rootViewController dismissViewControllerAnimated:NO completion:^{
            }];
            IVTBindingTelViewController *bindingTelVC = [[IVTBindingTelViewController alloc]init];
            bindingTelVC.platform = platform;
            [self.window.rootViewController presentViewController:bindingTelVC animated:YES completion:^{
                
            }];
        }
        else{
            NSMutableDictionary *dictid = [successData objectForKey:@"data"];
            NSString *msisdn = [NSString stringWithFormat:@"%@",[dictid objectForKey:@"msisdn"]];
            NSString *captcha = [NSString stringWithFormat:@"%@",[dictid objectForKey:@"captcha"]];
            
            [HUDUtil showLoading];
            [[IVTNetworkAPIClient sharedClient] loginWithPhone:msisdn captcha:captcha success:^(NSDictionary *successData) {
                [HUDUtil hide];
                [[XMPPManager sharedInstance] loginWithUserId:[IVTAccountTool getUserId] pwd:captcha];
                
                [IVTAccountTool getFollowListRequest];

                [self.window.rootViewController dismissViewControllerAnimated:YES completion:^{
                }];
            } error:^(NSDictionary *successData) {
                NSString *msg = successData[@"description"];
                [HUDUtil showError:msg];
            } failure:^(NSError *failureError) {
                [HUDUtil showError:@"网络异常"];
            }];
        }
    } error:^(NSDictionary *successData) {
        NSString *msg = successData[@"description"];
        [HUDUtil showError:msg];
    } failure:^(NSError *failureError) {
        [HUDUtil showError:@"网络异常"];
    }];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [TencentOAuth HandleOpenURL:url] || [WeiboSDK handleOpenURL:url delegate:self] || [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    return [TencentOAuth HandleOpenURL:url] || [WeiboSDK handleOpenURL:url delegate:self] || [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [TencentOAuth HandleOpenURL:url] || [WeiboSDK handleOpenURL:url delegate:self] || [WXApi handleOpenURL:url delegate:self];
}




- (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 {
    // 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.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (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
{
    
}
//    [self beingBackgroundUpdateTask];
//    
//    if (self.terminalDelegateDelegate && [self.terminalDelegateDelegate respondsToSelector:@selector(willTerminate:)])
//            {
//                [self.terminalDelegateDelegate willTerminate:@"已经被杀死~"];
//            }
//    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
//    [self endBackgroundUpdateTask];
//}
//
//- (void)beingBackgroundUpdateTask
//{
//    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
//        [self endBackgroundUpdateTask];
//    }];
//}
//
//- (void)endBackgroundUpdateTask
//{
//    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
//    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
//}

@end