AppDelegate.m 10.4 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//
//  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"
18
#import <AlipaySDK/AlipaySDK.h>
u  
lee committed
19
#import "AppDelegate+Deeplink.h"
houweibin committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33

@interface AppDelegate ()

@property (nonatomic) id customPushObserver;
@property (nonatomic) BOOL isFirst;//是否第一次进入

@end

@implementation AppDelegate{
    BOOL enterBackground;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
lee committed
34 35
//    [NSThread sleepForTimeInterval:1];
//    [_window makeKeyAndVisible];
houweibin committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    
    //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];
    //修改系统的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
    
    
    //首页还是引导页
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstTime"]) {
        [self toGuide];
    }else{
        [self toMain];
    }
u  
lee committed
80
    [self registerRouter];
houweibin committed
81 82 83 84 85
    
    [WXApi registerApp:WechatAppKey];
    return YES;
}

lee committed
86 87 88 89 90
+ (UIViewController *)mainViewController {
    UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    return vc;
}

houweibin committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
//去到引导界面
- (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];
}

117 118 119
//支付宝 NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
u  
lee committed
120 121 122 123
    if ([self handleURL:url]) {
        NSLog(@"trace openURL 9.0:%@",url);
        return YES;
    }
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    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;
}

//微信需要重写
houweibin committed
140
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
u  
lee committed
141 142 143 144
    if ([self handleURL:url]) {
        NSLog(@"trace handleOpenURL:%@",url);
        return YES;
    }
houweibin committed
145 146 147 148
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
u  
lee committed
149 150 151 152
    if ([self handleURL:url]) {
        NSLog(@"trace openURL 8.0:%@",url);
        return YES;
    }
houweibin committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    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;
        }
194 195 196 197 198 199 200 201 202 203 204 205
    }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;
        }
houweibin committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    }
}

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