KWMBaseVC.m 20.8 KB
Newer Older
houweibin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//
//  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"
houweibin committed
19 20
#import "KWMLoginVC.h"
#import "KWMUserModel.h"
houweibin committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38


@interface KWMBaseVC ()

@end

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

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

u  
lee committed
39 40 41 42 43
+ (NSString *)kwmBoard {
    [self doesNotRecognizeSelector:@selector(kwmBoard)];
    return nil;
}

houweibin committed
44 45 46 47 48 49 50
+ (KWMBaseVC *)findControllerBy:(NSString *)controllerId
                 fromStoryboard:(NSString *)storyboardName {
    UIStoryboard *myStoryboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    KWMBaseVC *baseController = [myStoryboard instantiateViewControllerWithIdentifier:controllerId];
    return baseController;
}

u  
lee committed
51 52 53 54
+ (instancetype) getNewInstance {
    return [self findControllerBy:[self kwmTag] fromStoryboard:[self kwmBoard]];
}

houweibin committed
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
- (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{
houweibin committed
279 280 281
    if([KWMStringUtil isEmpty:message]){
        return;
    }
houweibin committed
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    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, @"调用尚未实现的方法");
}

houweibin committed
304 305 306 307 308 309 310 311 312 313
- (void)initCustomTitleBarConstarints:(UIView *)titleView{
    id mTopLayoutGuide = self.topLayoutGuide;
    // 使用autoLayout约束,禁止将AutoresizingMask转换为约束
    [titleView setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSDictionary *views = NSDictionaryOfVariableBindings(titleView);
    NSDictionary *views2 = NSDictionaryOfVariableBindings(titleView,mTopLayoutGuide);
    [self.view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[titleView]|" options:0 metrics:nil views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[mTopLayoutGuide]-0-[titleView(44.0)]" options:0 metrics:nil views:views2]];
}

houweibin committed
314 315 316 317 318 319 320 321 322 323 324 325 326
-(BOOL)checkLogin{
    KWMUserModel *user = [KWMUserModel shareUser];
    if (user.status != 1) {
        //登录
        KWMLoginVC *loginVc = (KWMLoginVC *)[KWMBaseVC findControllerBy:[KWMLoginVC kwmTag] fromStoryboard:@"Login"];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
        return NO;
    }else{
        return YES;
    }
}

houweibin committed
327 328
//显示错误信息
- (void)showError:(NSError *)error{
329 330 331 332 333 334
    if (!error){
        return;
    }
    if ([error.domain isEqualToString:@"缓存错误"]){
        return;
    }
houweibin committed
335 336 337 338
    if ([error.domain isEqualToString:NSURLErrorDomain]) {
        [self showToast:@"网络已断开,请重新连接"];
        return;
    }
339
    if (!error.userInfo){
houweibin committed
340 341
        return;
    }
342
    if ([self isCheckOutError:error]){
houweibin committed
343 344
        return;
    }
345 346 347 348
    if ([self isSignUpError:error]){
        return;
    }
    if ([self isNormalError:error]){
houweibin committed
349 350
        return;
    }
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
    //如果并不是shopify error,则正常吐司。
    [self showToast:[error localizedDescription]];
}

-(BOOL)isCheckOutError:(NSError *)error{
    //虽然errorsFromCheckoutJSON里面有判断了,但为了保险起见,还是加上判断
    NSDictionary *errorsDictionary = error.userInfo[@"errors"];
    if(!errorsDictionary || ![errorsDictionary isKindOfClass:[NSDictionary class]]){
        return NO;
    }
    NSDictionary *customerDictionary = errorsDictionary[@"checkout"];
    if(!customerDictionary || ![customerDictionary isKindOfClass:[NSDictionary class]]){
        return NO;
    }
    NSArray<BUYError *> *errors = [BUYError errorsFromCheckoutJSON:error.userInfo];
//    现在下单时不会报quantity错误了。所以这段代码注释
//    if(errors && errors.count > 0){
//        NSString *quantityRemainingMessage = [errors.firstObject quantityRemainingMessage];
//    }
    if([self checkBuyErrors:errors]){
        return YES;
    }
    return NO;
}

-(BOOL)isSignUpError:(NSError *)error{
    NSDictionary *errorsDictionary = error.userInfo[@"errors"];
    if(!errorsDictionary || ![errorsDictionary isKindOfClass:[NSDictionary class]]){
        return NO;
    }
    NSDictionary *customerDictionary = errorsDictionary[@"customer"];
    if(!customerDictionary || ![customerDictionary isKindOfClass:[NSDictionary class]]){
        return NO;
    }
    NSArray<BUYError *> *errors = [BUYError errorsFromSignUpJSON:error.userInfo];
    if([self checkBuyErrors:errors]){
        return YES;
    }
    return NO;
}

- (BOOL)isNormalError:(NSError *)error{
    NSString *toast = [self getErrorMessage:error];
houweibin committed
394
    if(![KWMStringUtil isEmpty:toast]){
395
        if([toast isEqualToString:@"Unidentified customer"]){
houweibin committed
396 397 398
            toast = @"登录已失效,请重新登录";
        }
        [self showToast:toast];
399
        return YES;
houweibin committed
400
    }
401
    return NO;
houweibin committed
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
}

//判断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;
}

427
//获取key为message/error的错误信息
houweibin committed
428
- (NSString *)getErrorMessage:(NSError *)error{
429 430 431 432 433 434 435 436 437 438 439 440 441 442
    NSString *errorString;
    errorString = [self getErrorMessageForKey:@"message = \"" error:error];
    if(![KWMStringUtil isEmpty:errorString]){
        return errorString;
    }
    errorString = [self getErrorMessageForKey:@"error = \"" error:error];
    if(![KWMStringUtil isEmpty:errorString]){
        return errorString;
    }
    errorString = [self getErrorMessageForKey:@"errors = \"" error:error];
    if(![KWMStringUtil isEmpty:errorString]){
        return errorString;
    }
    return @"";
houweibin committed
443 444 445
}

-(NSString *)getErrorMessageForKey:(NSString *)key error:(NSError *)error{
446
    NSString *errorString = [self dictionaryToString:error.userInfo];
houweibin committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    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 @"";
}

//字典转换为字符串
463
- (NSString*)dictionaryToString:(NSDictionary *)dic{
houweibin committed
464 465 466 467
    NSString *a = [NSString stringWithFormat:@"%@",dic];
    return a;
}

468

houweibin committed
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 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
- (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];
}

554
- (MZFormSheetPresentationViewController *)showPresentation:(UIViewController *)vc size:(CGSize)size tapOutsideClose:(BOOL)tapOutsideClose style:(MZFormSheetPresentationTransitionStyle)style {
555 556 557 558 559 560 561 562 563 564 565
    MZFormSheetPresentationViewController *mz = [[MZFormSheetPresentationViewController alloc] initWithContentViewController:vc];
    mz.presentationController.shouldDismissOnBackgroundViewTap = tapOutsideClose;
    mz.presentationController.movementActionWhenKeyboardAppears = MZFormSheetActionWhenKeyboardAppearsCenterVertically;
    mz.contentViewControllerTransitionStyle = style;
    if (size.width > 0 && size.height > 0) {
        mz.presentationController.contentViewSize = size;
    }
    mz.presentationController.shouldCenterVertically = YES;
    [self presentViewController:mz
                       animated:YES
                     completion:nil];
566
    return mz;
567 568
}

houweibin committed
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614

/**将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