KWMBaseVC.m 17.1 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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 80 81 82 83 84 85 86 87 88 89 90 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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 194 195 196 197 198 199 200 201 202 203 204 205 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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
//
//  KWMBaseVC.m
//  iBallsoul
//
//  Created by Yaotian on 3/25/16.
//  Copyright © 2016 kwm. All rights reserved.
//

#import "KWMBaseVC.h"
#import "KWMAPIManager.h"
#import "KWMImageUtil.h"
#import "KWMImageUtil.h"
#import "UIColor+SAMAdditions.h"
#import "RTSpinKitView.h"
#import "MBProgressHUD.h"
#import "PSPDFAlertView.h"
#import "KWMStringUtil.h"
#import "KWMSuperLoadingView.h"


@interface KWMBaseVC ()

@end

@implementation KWMBaseVC{
    UIView *vLoadingContainer;
//    RTSpinKitView *loadingView;
    KWMSuperLoadingView *loadingView;
    int showLoadingCount;
    MBProgressHUD *toastHUD;
}

+ (NSString *)kwmTag {
    return NSStringFromClass([self class]);
}

+ (KWMBaseVC *)findControllerBy:(NSString *)controllerId
                 fromStoryboard:(NSString *)storyboardName {
    UIStoryboard *myStoryboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    KWMBaseVC *baseController = [myStoryboard instantiateViewControllerWithIdentifier:controllerId];
    return baseController;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
//    self.view.backgroundColor = [UIColor sam_colorWithHex:@"#F1F1F1"];
//    [self setupForDismissKeyboard];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:NO];
//    [MobClick beginLogPageView:[NSStringFromClass(self Class)]];
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillShow:)
                               name:UIKeyboardWillShowNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillHide:)
                               name:UIKeyboardWillHideNotification
                             object:nil];
    
    [notificationCenter addObserver:self
                           selector:@selector(keyboardWillChangeFrame:)
                               name:UIKeyboardWillChangeFrameNotification
                             object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self hideLoading];
//    [MobClick endLogPageView:[NSStringFromClass(self Class)]];
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self
                                  name:UIKeyboardWillShowNotification
                                object:nil];
    
    [notificationCenter removeObserver:self
                                  name:UIKeyboardWillHideNotification
                                object:nil];
    
    [notificationCenter removeObserver:self
                                  name:UIKeyboardWillChangeFrameNotification
                                object:nil];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if (self.keyboardHeight <= 0) {
        return;
    }
    self.keyboardHeight = 0;
}

- (void)keyboardWillShow:(NSNotification *)notification {
    if (self.keyboardHeight > 0) {
        return;
    }
    
    self.keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    self.keyboardHeight = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
}

- (KWMAPIManager *)api {
    if (_api == nil) {
        _api = [KWMAPIManager sharedManager];
    }
    return _api;
}

- (BUYClient *)client {
    if (_client == nil){
        _client = [[BUYClient alloc] initWithShopDomain:Shopify_SHOP_DOMAIN
                                                     apiKey:Shopify_API_KEY
                                                      appId:Shopify_APP_ID];

    }
    _client.pageSize = 20;
    NSDictionary *tokenDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    NSString *path = NSHomeDirectory();//主目录
    NSLog(@"NSHomeDirectory:%@",path);
    if (tokenDic != nil) {
        BUYCustomerToken *token = [BUYCustomerToken customerTokenWithJSONDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]];
        if (token != nil) {
            _client.customerToken = token;
        }
    }
    return _client;
}


- (KWMUserDao *)userDao {
    if (_userDao == nil) {
        _userDao = [KWMUserDao shareDao];
    }
    return _userDao;
}

- (AppDelegate *)appDelegate {
    if(_appDelegate == nil){
        _appDelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    }
    return _appDelegate;
}

- (void)showLoading {
    
//    UIView * contentView = (self.navigationController.view != nil) ? self.navigationController.view : self.view;
    UIView *contentView = self.view;
    [self showLoading:contentView cancelable:NO];
    
}

- (void)showLoading:(UIView *)view cancelable:(BOOL)isCancelable loadingBg:(UIColor *) color{
    if(view == nil){
        return;
    }
    
    showLoadingCount++;
    
    if (loadingView == nil) {
        //初始化加载页面
//        loadingView = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStylePlane color:[UIColor sam_colorWithHex:@"#242424"]];
        loadingView = [[KWMSuperLoadingView alloc] initWithFrame:CGRectMake((UI_SCREEN_WIDTH-30)*0.5, (UI_SCREEN_HEITHT - 30)*0.5, 30, 30)];
        vLoadingContainer = [[UIView alloc] initWithFrame:CGRectZero];
        vLoadingContainer.frame = view.frame;
        vLoadingContainer.backgroundColor = color;
        
        CGPoint center = vLoadingContainer.center;
        center.y = center.y;
        loadingView.center = center;
        [loadingView initLoadingView];
        [loadingView startAnimation];
        [vLoadingContainer addSubview:loadingView];
        [view addSubview:vLoadingContainer];
    }else{
        vLoadingContainer.backgroundColor = color;
    }
    
    vLoadingContainer.hidden = NO;
    loadingView.hidden = NO;
    vLoadingContainer.userInteractionEnabled = YES;
//    [loadingView startAnimating];
    [loadingView startAnimation];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    NSLog(@"showLoading count=%d", showLoadingCount);
}

- (void)showLoading:(UIView *)view cancelable:(BOOL)isCancelable {
    [self showLoading:view cancelable:isCancelable loadingBg:[UIColor clearColor]];
}

-(void) hideLoading:(BOOL)isDelay{
    
    showLoadingCount--;
    if(showLoadingCount <= 0){
        showLoadingCount = 0;
        if(loadingView != nil){
            loadingView.hidden = YES;
            vLoadingContainer.hidden = YES;
//            [loadingView stopAnimating];
            [loadingView stopAnimation];
        }
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"hideLoading count=%d", showLoadingCount);
    
}

- (void)hideLoading {
    
//    if (showLoadingCount <= 0) {
//        return;
//    }
//    
//    //隐藏图标显示登录页面
    CABasicAnimation *theAnimation;
    theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
    theAnimation.duration= 0.6f;
    theAnimation.autoreverses = NO;
    theAnimation.repeatCount = 0;
    theAnimation.removedOnCompletion = NO;
    theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
    theAnimation.toValue=[NSNumber numberWithFloat:0.0];
    [loadingView.layer addAnimation:theAnimation forKey:@"animateOpacity"];
    
    [self performSelector:@selector(hideLoading:) withObject:nil afterDelay:0.5f];
}

- (void)showToast:(NSString *)message{
    if (message.length >= 40) {
        [self showDialog:message];
        return;
    }
    if(toastHUD != nil){
        [toastHUD hide:NO];
        toastHUD = nil;
    }
    UIView * contentView = self.navigationController.view != nil ? self.navigationController.view : self.view;
    if(contentView == nil){
        return;
    }
    CGSize widthSize = [KWMStringUtil boundingRectWithSize:CGSizeMake(UI_SCREEN_WIDTH - 100, 0) text:message testSize:15];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, widthSize.width, widthSize.height)];
    view.backgroundColor = [UIColor clearColor];
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, widthSize.width, widthSize.height)];
    [messageLabel setFont:[UIFont systemFontOfSize:15.0]];
    messageLabel.textColor = [UIColor whiteColor];
    messageLabel.text = message;
    messageLabel.numberOfLines = 0;
    [view addSubview:messageLabel];
    
    toastHUD = [MBProgressHUD showHUDAddedTo:contentView animated:YES];
    toastHUD.userInteractionEnabled = NO;
    toastHUD.mode = MBProgressHUDModeCustomView;
    toastHUD.customView = view;
    toastHUD.removeFromSuperViewOnHide = YES;
    [toastHUD hide:YES afterDelay:2];
}

- (void)showDialog:(NSString *)message{
    PSPDFAlertView *alertView = [[PSPDFAlertView alloc] initWithTitle:message];
    [alertView addButtonWithTitle:@"确定" block:nil];
    [alertView show];
}


- (void)showEmptyView:(NSInteger)type setTips:(NSString *)tips{
    //TODO 显示数据为空的界面
}

- (void)hideEmptyView {
    
}

- (void)reLoadData {
    NSAssert(NO, @"调用尚未实现的方法");
}

- (void)loadData {
    NSAssert(NO, @"调用尚未实现的方法");
}

//显示错误信息
- (void)showError:(NSError *)error{
    if ([error.domain isEqualToString:NSURLErrorDomain]) {
        [self showToast:@"网络已断开,请重新连接"];
//        [self showToast:@"请求数据失败"];
        return;
    }
//    NSDictionary *userInfo = [error userInfo];
//    if (userInfo != nil) {
//        NSNumber *errorCodeKey = [userInfo objectForKey:@"_kCFStreamErrorCodeKey"];
//        if (errorCodeKey.intValue == 8) {
//            [self showToast:@"网络已断开,请重新连接"];
//            return;
//        }
//    }
    NSArray<BUYError *> *errors = [BUYError errorsFromCheckoutJSON:error.userInfo];
    if([self checkBuyErrors:errors]){
        return;
    }
    errors = [BUYError errorsFromSignUpJSON:error.userInfo];
    if([self checkBuyErrors:errors]){
        return;
    }
    NSString *toast = [self getErrorMessage:error];
    if(![KWMStringUtil isEmpty:toast]){
        [self showToast:toast];
        return;
    }
    toast = [self getErrorMessage2:error];
    if(![KWMStringUtil isEmpty:toast]){
        if(toast!=nil && [toast isEqualToString:@"Unidentified customer"]){
            toast = @"登录已失效,请重新登录";
        }
        [self showToast:toast];
        return;
    }

    [self showToast:[error localizedDescription]];
}

//判断buyerror是否有效,有效则吐司错误
-(BOOL)checkBuyErrors:(NSArray<BUYError *>*)errors{
    if(errors!=nil && errors.count>0){
        for(BUYError *error in errors){
            if(error != nil && error != NULL && ![error isKindOfClass:[NSNull class]]){
                NSString *key = error.key;
                if(key == nil){
                    break;
                }
                if([error.key isEqualToString:@"quantity"]){
                    key = @"商品剩余不足";
                }else if([error.key isEqualToString:@"address"]){
                    key = @"地址出错";
                }
                NSString *toast = [NSString stringWithFormat:@"%@, %@",key,error.message];
                [self showToast:toast];
                return YES;
            }
        }
    }
    return NO;
}

//获取key为message的错误信息
- (NSString *)getErrorMessage:(NSError *)error{
    return [self getErrorMessageForKey:@"message = \"" error:error];
}

//获取key为error的错误信息
- (NSString *)getErrorMessage2:(NSError *)error{
    return [self getErrorMessageForKey:@"error = \"" error:error];
}

-(NSString *)getErrorMessageForKey:(NSString *)key error:(NSError *)error{
    NSString *errorString = [self dictionaryToJson:error.userInfo];
    NSRange startRange = [errorString rangeOfString:key];
    if (startRange.location != NSNotFound) {
        NSString *errorString2 = [errorString substringFromIndex:startRange.location + startRange.length];
        NSRange endRange = [errorString2 rangeOfString:@"\""];
        
        if(endRange.location != NSNotFound){
            NSString *errorMessage = [errorString2 substringToIndex:endRange.location];
            return errorMessage;
        }
    }else{
        NSLog(@"Not Found");
    }
    return @"";
}

//字典转换为字符串
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSString *a = [NSString stringWithFormat:@"%@",dic];
    return a;
}

- (BOOL)hasError:(id)result{
    
    NSInteger code = -1;
    NSString *message;
    if ([result isKindOfClass:[KWMRequestResult class]]) {
        KWMRequestResult *r = result;
        code = r.code;
        message = r.message;
    }
    if ([result isKindOfClass:[KWMRequestListResult class]]) {
        KWMRequestListResult *r = result;
        code = r.code;
        message = r.message;
    }
    
    BOOL isError = code != 0;
    if (isError) {
        if (code == 1) {
            //未登录,已经在APIManager里面发广播了
        }else{
            [self showToast:message];
        }
    }
    return isError;
}

-(BOOL)hasCemaroseError:(KWMCemaroseResult *)result{
    BOOL isError = NO;
    if(!result){
        [self showToast:@"获取数据失败"];
        isError = YES;
    }else if(result.success && !result.success.boolValue){
        [self showToast:result.msg];
        isError = YES;
    }
    return isError;
}

- (void)popDelay {
    [self popDelay:0.3f];
}

- (void)popDelay:(NSTimeInterval)sec {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (void (^)(NSURLSessionDataTask *, NSError *))defaultFailure {
    __weak KWMBaseVC *weakSelf = self;
    return ^(NSURLSessionDataTask *task, NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showError:error];
    };
}


- (void)transparentNavigationBar {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
}

- (void)unTransparentNavigationBar {
    UIImage *image = [KWMImageUtil createColorImage:[UIColor sam_colorWithHex:@"FF982B"]];
    [self.navigationController.navigationBar setBackgroundImage:image
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.navigationController.navigationBar.translucent = NO;
}

- (UIBarButtonItem *)createBarButtonItem:(NSString *)title
                                   image:(UIImage *)image
                                  action:(SEL)action{
    UIButton *btnView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    btnView.backgroundColor = [UIColor clearColor];
//    btnView.titleLabel.textColor = [UIColor whiteColor];
//    [btnView setTitle:title forState:UIControlStateNormal];
    [btnView setImage:image forState:UIControlStateNormal];
    [btnView addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    
    return [[UIBarButtonItem alloc] initWithCustomView:btnView];
}


/**将URL转成UIImage*/
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
    __block UIImage *sharImage;
    if (!(options & SDWebImageDelayPlaceholder)) {
        dispatch_main_async_safe(^{
            sharImage = placeholder;
        });
    }
    if (url) {
        __weak __typeof(self)wself = self;
        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            if (!wself) return;
            dispatch_main_sync_safe(^{
                if (!wself) return;
                if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock)
                {
                    completedBlock(image, error, cacheType, url);
                    return;
                }
                else if (image) {
                    sharImage = image;
                } else {
                    if ((options & SDWebImageDelayPlaceholder)) {
                        sharImage = placeholder;
                        
                    }
                }
                if (completedBlock && finished) {
                    completedBlock(image, error, cacheType, url);
                }
            });
        }];
    } else {
        dispatch_main_async_safe(^{
            
            NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
            if (completedBlock) {
                completedBlock(nil, error, SDImageCacheTypeNone, url);
            }
        });
    }
    
}

@end