// // AppDelegate.m // iToYoung // // Created by Yaotian on 5/13/16. // Copyright © 2016 Kollway. All rights reserved. // #import "AppDelegate.h" #import "UIColor+SAMAdditions.h" #import "KWMImageUtil.h" #import "KWMUserDao.h" #import "KWMUser.h" #import "KWMStringUtil.h" #import "KWMGuideVC.h" #import "KWMLoginVC.h" #import "KWMUserModel.h" #import <AlipaySDK/AlipaySDK.h> #import "AppDelegate+Deeplink.h" #import "DeepLinkURLProtocol.h" @interface AppDelegate () @property (nonatomic) id customPushObserver; @property (nonatomic) BOOL isFirst;//是否第一次进入 @end @implementation AppDelegate{ BOOL enterBackground; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // [NSThread sleepForTimeInterval:1]; // [_window makeKeyAndVisible]; //UI: Appearance [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; [[UINavigationBar appearance] setTintColor:[UIColor sam_colorWithHex:@"333333"]]; [[UINavigationBar appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName: [UIColor sam_colorWithHex:@"333333"], NSFontAttributeName: [UIFont systemFontOfSize:18.0f]}]; //去掉navigationbar底部的黑线 [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault]; [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]]; [[UINavigationBar appearance] setBackgroundImage:[KWMImageUtil createColorImage:[UIColor sam_colorWithHex:@"FFFFFF"]] forBarMetrics:UIBarMetricsDefault]; //navigationbar樣式 [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]]; [[UINavigationBar appearance] setTranslucent:NO]; //改变所有输入框的光标颜色 [[UITextField appearance] setTintColor:[UIColor sam_colorWithHex:@"F1929A"]]; //去掉返回按钮的文字 // [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-UI_SCREEN_WIDTH, -UI_SCREEN_HEITHT) forBarMetrics:UIBarMetricsDefault]; [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-200, 0) forBarMetrics:UIBarMetricsDefault]; //修改系统的backbutton的图片 [UINavigationBar appearance].backIndicatorTransitionMaskImage = [UIImage imageNamed:@"btn_nav_back"]; [UINavigationBar appearance].backIndicatorImage = [UIImage imageNamed:@"btn_nav_back"]; [UINavigationBar appearance].shadowImage = [UIImage new]; // CoreData 初始化 [MagicalRecord setupCoreDataStackWithStoreNamed:@"DB_shopCart"]; // [self cleanAndResetupDB]; BOOL isProduction = YES; #ifdef DEBUG isProduction = NO; #endif // 注册DeepLinkURLProtocol 来实现App内H5跳转 [NSURLProtocol registerClass:[DeepLinkURLProtocol class]]; //首页还是引导页 if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstTime"]) { [self toGuide]; }else{ [self toMain]; } [self registerRouter]; [WXApi registerApp:WechatAppKey]; return YES; } + (UIViewController *)mainViewController { UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; return vc; } //去到引导界面 - (void)toGuide{ UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Guide" bundle:nil]; UIViewController *guideVC = [storyboard instantiateViewControllerWithIdentifier:@"KWMGuideVC"]; self.window.rootViewController = guideVC; [self.window makeKeyAndVisible]; } //去到主界面 - (void)toMain{ UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIViewController *mainVC = [storyboard instantiateViewControllerWithIdentifier:@"KWMMainVC"]; self.window.rootViewController = mainVC; [self.window makeKeyAndVisible]; } //去到登录界面 - (void)toLogin { // UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; // UIViewController *mainVC = [storyboard instantiateViewControllerWithIdentifier:@"KWMMainVC"]; // self.window.rootViewController = mainVC; // [self.window makeKeyAndVisible]; } //支付宝 NOTE: 9.0以后使用新API接口 - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options { if ([self handleURL:url]) { NSLog(@"trace openURL 9.0:%@",url); return YES; } if ([url.host isEqualToString:@"safepay"]) { //跳转支付宝钱包进行支付,处理支付结果 [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) { NSLog(@"result = %@",resultDic); NSNumber *statue = [resultDic objectForKey:@"resultStatus"]; if (statue.integerValue == 9000) { [[NSNotificationCenter defaultCenter] postNotificationName:KWMPaySuccess object:nil userInfo:nil]; } }]; }else{//ios9.2之后的系统需要调用(官方文档没有) return [WXApi handleOpenURL:url delegate:self]; } return YES; } //微信需要重写 -(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{ if ([self handleURL:url]) { NSLog(@"trace handleOpenURL:%@",url); return YES; } return [WXApi handleOpenURL:url delegate:self]; } -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{ if ([self handleURL:url]) { NSLog(@"trace openURL 8.0:%@",url); return YES; } return [WXApi handleOpenURL:url delegate:self]; } #pragma mark - #pragma mark WXApiDelegate 微信分享的相关回调 //onReq是微信终端向第三方程序发起请求,要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时,会切回到微信终端程序界面。 - (void)onReq:(BaseReq *)req { } //如果第三方程序向微信发送了sendReq的请求,那么onResp会被回调。sendReq请求调用后,会切到微信终端程序界面。 //enum WXErrCode { // WXSuccess = 0, /**< 成功 */ // WXErrCodeCommon = -1, /**< 普通错误类型 */ // WXErrCodeUserCancel = -2, /**< 用户点击取消并返回 */ // WXErrCodeSentFail = -3, /**< 发送失败 */ // WXErrCodeAuthDeny = -4, /**< 授权失败 */ // WXErrCodeUnsupport = -5, /**< 微信不支持 */ //}; - (void)onResp:(BaseResp *)resp { if([resp isKindOfClass:[SendMessageToWXResp class]]) { switch (resp.errCode) { case WXSuccess: { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"成功" message:@"微信分享成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; } break; case WXErrCodeUserCancel: break; default: { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败" message:@"微信分享失败" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; } break; } }else if([resp isKindOfClass:[PayResp class]]){ NSString *strMsg = @""; switch (resp.errCode) { case WXSuccess: NSLog(@"支付成功"); [[NSNotificationCenter defaultCenter] postNotificationName:KWMPaySuccess object:nil userInfo:nil]; break; default: strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr]; NSLog(@"支付错误信息%@", strMsg); break; } } } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { /// Required - 注册 DeviceToken // [JPUSHService registerDeviceToken:deviceToken]; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // Required,For systems with less than or equal to iOS6 // [JPUSHService handleRemoteNotification:userInfo]; // [self handlePush:userInfo]; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // IOS 7 Support Required // [JPUSHService handleRemoteNotification:userInfo]; // [self handlePush:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { //Optional NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error); } - (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 { enterBackground = YES; [UIApplication sharedApplication].applicationIconBadgeNumber = 0; } - (void)applicationWillEnterForeground:(UIApplication *)application { //进入前台,延迟半秒之后算进入应用 [self performSelector:@selector(initViewStatus) withObject:nil afterDelay:0.5]; } - (void)applicationDidBecomeActive:(UIApplication *)application { [UIApplication sharedApplication].applicationIconBadgeNumber = 0; } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. //清除CoreData [MagicalRecord cleanUp]; } -(void)initViewStatus{ enterBackground = NO; } //清除重设置数据库 - (void)cleanAndResetupDB{ NSString *dbStore = @"DB_shopCart"; NSError *error1 = nil; NSURL *storeURL = [NSPersistentStore MR_urlForStoreName:dbStore]; [MagicalRecord cleanUp]; if([[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error1]){ //Core Data [MagicalRecord setupCoreDataStackWithStoreNamed:@"DB_shopCart"]; } else{ NSLog(@"An error has occurred while deleting %@", dbStore); } } @end