YHExplorerViewController.m 22.7 KB
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 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 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 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 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
//
//  YHExplorerViewController.m
//  YohoExplorerDemo
//
//  Created by gaoqiang xu on 2/27/15.
//  Copyright (c) 2015 gaoqiang xu. All rights reserved.
//

static float kprogressViewHeight = 2.0f;
static float kprogressViewRadius = 2.0f;

#import "YHExplorerViewController.h"
#import "YHWebViewProgress.h"
#import "YHWebViewProgressView.h"
#import "CDVUIWebViewEngine.h"
#import "CDVWKWebViewEngine.h"
#import <objc/message.h>
#import "YHInjectJsCordovaManager.h"

@interface YHExplorerViewController ()<UIWebViewDelegate, WKNavigationDelegate, WKUIDelegate>
{
    BOOL _scalesPageToFit;
}

@property (strong, nonatomic) NSURLRequest *originRequest;

@property (strong, nonatomic) YHWebViewProgress *progressBar;
@property (strong, nonatomic) YHWebViewProgressView *progressView;

@property (nonatomic) BOOL isAppeared;
@property (strong, nonatomic) NSMutableArray *linkParsers;

@property (strong, nonatomic) NSValue *pointerValue;

@end

@implementation YHExplorerViewController


- (void)dealloc
{
    [self stopLoading];
    
    self.progressBar = nil;
    [self removeProgress];
    self.progressView = nil;
    
    if ([self.webViewEngine isKindOfClass:NSClassFromString(@"CDVWKWebViewEngine").class]) {
        [self.webView removeObserver:self forKeyPath:@"title"];
    }
}

- (void)initializeExplorer
{
    _commandDelegate = [[YHExplorerCommandDelegate alloc] initWithViewController:self];
    _commandQueue = [[YHExplorerCommandQueue alloc] initWithViewController:self];
    _progressBarEnabled = NO;
    _automaticallySchemeHandle = YES;
}

- (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self initializeExplorer];
    }
    return self;
}

- (instancetype)initWithCurrentNaviBar:(UINavigationBar *)currentNaviBar
{
    self = [self init];
    if (self) {
        self.currentNaviBar = currentNaviBar;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.isAppeared = NO;
    
    YHLinkDefaultParser *parser = [[YHLinkDefaultParser alloc] init];
    [self registerLinkParser:parser];
    
    if (self.progressBar && !self.progressBar.progressView.superview) {
        [self.currentNaviBar addSubview:self.progressBar.progressView];
    }
    
    if ([self.webViewEngine isKindOfClass:NSClassFromString(@"CDVWKWebViewEngine")]) {
        [self.progressView useWkWebView:(WKWebView *)self.webView];
        [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return [super shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.isAppeared = YES;
    if (self.progressBar) {
        if (!self.progressBar.progressView.superview) {
            [self.currentNaviBar addSubview:self.progressBar.progressView];
        } else {
            [self.currentNaviBar bringSubviewToFront:self.progressBar.progressView];
        }
    }
}

/**
 *  移除滚动条
 */
- (void)removeProgress
{
    if (self.progressView) {
        [self.progressView removeFromSuperview];
    }
}

#pragma mark - Override Setter & Getter
- (NSMutableArray *)linkParsers
{
    if (!_linkParsers) {
        _linkParsers = [[NSMutableArray alloc] initWithCapacity:1];
    }
    return _linkParsers;
}

- (void)setProgressBarEnabled:(BOOL)progressBarEnabled
{
    if (_progressBarEnabled == progressBarEnabled) {
        return;
    }
    
    _progressBarEnabled = progressBarEnabled;
    
    if (progressBarEnabled) {
        self.progressView.layer.cornerRadius = kprogressViewRadius;
        
        [self.progressView setFrame:CGRectMake(0, 41 , CGRectGetWidth(self.view.frame), kprogressViewHeight)];
        self.progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin;
        if (self.isAppeared) {
            [_currentNaviBar addSubview:self.progressView];
        }
        _progressBar.progressView = self.progressView;
        
        _progressBar = [[YHWebViewProgress alloc] init];
        _progressBar.progressView = self.progressView;
        
    } else {
        if (self.progressBar) {
            [self.progressBar.progressView removeFromSuperview];
            self.progressBar = nil;
        }
    }
}

- (YHWebViewProgressView *)progressView
{
    static YHWebViewProgressView *sharedProgressViewInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedProgressViewInstance = [[YHWebViewProgressView alloc] init];
    });
    return sharedProgressViewInstance;
}

- (NSMutableArray *)autoSchemes
{
    if (!_autoSchemes) {
        _autoSchemes = [[NSMutableArray alloc] initWithObjects:
                        @"itms-apps",
                        @"itms-appss",
                        @"itmss",
                        @"tel",
                        @"sms",
                        @"mailto",
                        @"yohoefashion4in1",
                        @"yohomars", nil];
    }
    return _autoSchemes;
}

- (NSMutableArray *)autoHosts
{
    if (!_autoHosts) {
        _autoHosts = @[@"itunes.apple.com"].mutableCopy;
    }
    return _autoHosts;
}

- (NSValue *)pointerValue
{
    if (!_pointerValue) {
        _pointerValue = [NSValue valueWithPointer:(__bridge const void *)(self)];
    }
    return _pointerValue;
}

- (NSString*)userAgent
{
    _userAgent = [super userAgent];
    if ([self.delegate respondsToSelector:@selector(extraUserAgent)]) {
        NSString *ua = [self.delegate extraUserAgent];
        if (ua.length) {
            return [NSString stringWithFormat:@"%@ %@", _userAgent, ua];
        }
    }
    return _userAgent;
}

#pragma mark - Public
- (instancetype)initWithUrl:(NSString *)url
{
    self = [self init];
    if (self) {
        self.startPage = url;
    }
    
    return self;
}

- (void)loadWebUrl:(NSString *)urlStr
{
    NSURL *URL = nil;
    if (urlStr.length > 0) {
        URL = [NSURL URLWithString:urlStr];
        if (URL == nil) {
            // 如果url里面含有需要转码的字符,则这里进行一次编码
            urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            URL = [NSURL URLWithString:urlStr];
        }
    }
    [self loadURL:URL];
}

- (void)loadURL:(NSURL *)URL
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    self.originRequest = request;

    if ([self.delegate respondsToSelector:@selector(explorerWillLoadRequest:)]) {
        [self.delegate explorerWillLoadRequest:request];
    }
    self.startPage = request.URL.absoluteString;
    [self.webViewEngine loadRequest:request];
}

- (void)loadHTMLString:(NSString *)html
{
    [self.webViewEngine loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}

- (void)loadHTMLString:(NSString *)html baseURL:(nullable NSURL *)baseURL
{
    [self.webViewEngine loadHTMLString:html baseURL:baseURL];
}

- (void)setProgressBarColor:(UIColor *)color
{
    if (self.progressBar) {
        YHWebViewProgressView *view = (YHWebViewProgressView *)self.progressBar.progressView;
        view.progressBarColor = color;
    }
}

- (void)registerLinkParser:(id <YHLinkParserDelegate>)parser
{
    if ([self.linkParsers containsObject:parser]) {
        return;
    }
    
    __weak typeof(self)weakSelf = self;
    parser.completion = ^(NSDictionary *result) {
        [weakSelf parseFinishedWithResult:result];
    };
    
    [self.linkParsers addObject:parser];
}

- (void)unRegisterLinkParser:(id <YHLinkParserDelegate>)parser
{
    [self.linkParsers removeObject:parser];
}

#pragma mark - Private
- (void)parseFinishedWithResult:(NSDictionary *)result
{
    if ([self.delegate respondsToSelector:@selector(explorerDidDetectParameters:)])
    {
        [self.delegate explorerDidDetectParameters:result];
    }
    
    if ([self.delegate respondsToSelector:@selector(explorer:didDetectParameters:)]) {
        [self.delegate explorer:self didDetectParameters:result];
    }
}

#pragma mark - UIWebDelegate

- (void)webViewDidStartLoad:(UIWebView*)theWebView
{
    if (self.progressBar) {
        [self.progressBar webViewDidStartLoad:theWebView];
    }
    [self callback_webViewDidStartLoad];
}

- (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    [[YHInjectJsCordovaManager sharedInstance] cycleInject:theWebView];
    
    if (self.originRequest == nil) {
        self.originRequest = theWebView.request;
    }
    
    NSString *title = [theWebView stringByEvaluatingJavaScriptFromString: @"document.title"];
    _pageTitle = title;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageTitleUpdated:)]) {
        [self.delegate pageTitleUpdated:title];
    }
    
    if (self.progressBar) {
        [self.progressBar webViewDidFinishLoad:theWebView];
    }
    
    [self callback_webViewDidFinishLoad];
    
    NSString *key = [[NSString alloc] initWithFormat:@"WebKit%@%@", @"CacheModel", @"PreferenceKey"];//WebKitCacheModelPreferenceKey
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
{
    if (self.progressBar) {
        [self.progressBar webView:theWebView didFailLoadWithError:error];
    }
    [self callback_webViewDidFailLoadWithError:error];
}

- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (self.progressBar && [self.progressBar checkIfRPCURL:request]) {
        return NO;
    }
    
    BOOL currentShouldStartLoadWithRequest = [self callback_webViewShouldStartLoadWithRequest:request navigationType:navigationType];
    
    if (self.progressBar && currentShouldStartLoadWithRequest) {
        currentShouldStartLoadWithRequest = [self.progressBar webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    
    return currentShouldStartLoadWithRequest;
}


#pragma mark WKNavigationDelegate implementation
//页面开始加载时调用 1
- (void)webView:(WKWebView*)webView didStartProvisionalNavigation:(WKNavigation*)navigation
{
    [self callback_webViewDidStartLoad];
}

// 页面加载完成之后调用 2
- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation
{
    [self callback_webViewDidFinishLoad];
}
// 页面加载失败时调用
- (void)webView:(WKWebView*)theWebView didFailProvisionalNavigation:(WKNavigation*)navigation withError:(NSError*)error
{
    [self callback_webViewDidFailLoadWithError:error];
}
// 数据加载发生错误时调用
- (void)webView:(WKWebView*)theWebView didFailNavigation:(WKNavigation*)navigation withError:(NSError*)error
{
    [self callback_webViewDidFailLoadWithError:error];
}
// 进程被终止时调用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    [webView reload];
}

//在发送请求之前,决定是否跳转
- (void)webView: (WKWebView *) webView decidePolicyForNavigationAction: (WKNavigationAction*) navigationAction decisionHandler: (void (^)(WKNavigationActionPolicy)) decisionHandler
{
    NSURLRequest *request = navigationAction.request;
    BOOL result = [self callback_webViewShouldStartLoadWithRequest:request navigationType:navigationAction.navigationType];
    if (result) {
        decisionHandler(WKNavigationActionPolicyAllow);
    } else {
        decisionHandler(WKNavigationActionPolicyCancel);
    }
}

#pragma mark - WKUIDelegate
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

#pragma mark - WebViewDelegate Callback
- (void)callback_webViewDidStartLoad
{
    [self.commandQueue resetRequestId];
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webViewDidStartLoad:)])
    {
        [self.delegate yhExplorer_webViewDidStartLoad:self];
    }
}

- (void)callback_webViewDidFinishLoad
{
    [CDVUserAgentUtil releaseLock:self.userAgentLockToken];
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webViewDidFinishLoad:)])
    {
        [self.delegate yhExplorer_webViewDidFinishLoad:self];
    }
}

- (void)callback_webViewDidFailLoadWithError:(NSError *)error
{
    [CDVUserAgentUtil releaseLock:self.userAgentLockToken];
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webView:didFailLoadWithError:)])
    {
        [self.delegate yhExplorer_webView:self didFailLoadWithError:error];
    }
}

- (BOOL)callback_webViewShouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(NSInteger)navigationType
{
    if ([self.delegate respondsToSelector:@selector(yhExplorer_webView:shouldStartLoadWithRequest:navigationType:)])
    {
        if (![self.delegate yhExplorer_webView:self shouldStartLoadWithRequest:request navigationType:navigationType]) {
            return NO;
        }
    }
    
    NSURL *url = [request URL];
    
    /*
     * Execute any commands queued with cordova.exec() on the JS side.
     * The part of the URL after gap:// is irrelevant.
     */
    if ([[url scheme] isEqualToString:@"gap"]) {
        [self.commandQueue fetchCommandsFromJs];
        // The delegate is called asynchronously in this case, so we don't have to use
        // flushCommandQueueWithDelayedJs (setTimeout(0)) as we do with hash changes.
        [self.commandQueue executePending];
        return NO;
    }
    
    if (self.automaticallySchemeHandle) {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            NSArray *array = [self.autoSchemes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", url.scheme]];
            if (array.count > 0) {
                [[UIApplication sharedApplication] openURL:url];
                return NO;
            }
            array = [self.autoHosts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", url.host]];
            if (array.count > 0) {
                [[UIApplication sharedApplication] openURL:url];
                return NO;
            }
        }
    }
    
    /*
     * Give plugins the chance to handle the url
     */
    
    if (navigationType == -1/*WKNavigationTypeOther*/)
    {
        navigationType = UIWebViewNavigationTypeOther;
    }
    
    BOOL anyPluginsResponded = NO;
    BOOL shouldAllowRequest = NO;
    
    for (NSString* pluginName in self.pluginObjects) {
        CDVPlugin* plugin = [self.pluginObjects objectForKey:pluginName];
        SEL selector = NSSelectorFromString(@"shouldOverrideLoadWithRequest:navigationType:");
        if ([plugin respondsToSelector:selector]) {
            anyPluginsResponded = YES;
            shouldAllowRequest = (((BOOL (*)(id, SEL, id, int))objc_msgSend)(plugin, selector, request, (UIWebViewNavigationType)navigationType));
            if (!shouldAllowRequest) {
                break;
            }
        }
    }

    if (anyPluginsResponded) {
        return shouldAllowRequest;
    }
    return YES;
}

#pragma mark - WebViewProtocol

- (UIScrollView *)scrollView
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        return [(UIWebView *)self.webView scrollView];
    } else if ([self.webView isKindOfClass:[WKWebView class]]) {
        return [(WKWebView *)self.webView scrollView];
    }
    return nil;
}

- (NSURL *)requestURL
{
    return [self.webViewEngine URL];
}

- (BOOL)canGoBack
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        return [(UIWebView *)self.webView canGoBack];
    } else if ([self.webView isKindOfClass:[WKWebView class]]) {
        return [(WKWebView *)self.webView canGoBack];
    }
    return NO;
}

- (BOOL)canGoForward
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        return [(UIWebView *)self.webView canGoForward];
    } else if ([self.webView isKindOfClass:[WKWebView class]]) {
        return [(WKWebView *)self.webView canGoForward];
    }
    return NO;
}

- (id)goBack
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        [(UIWebView *)self.webView goBack];
        return nil;
    } else if ([self.webView isKindOfClass:[WKWebView class]]) {
        return [(WKWebView *)self.webView goBack];
    }
    return nil;
}

- (id)goForward
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        [(UIWebView *)self.webView goForward];
        return nil;
    } else if ([self.webView isKindOfClass:[WKWebView class]]) {
        return [(WKWebView *)self.webView goForward];
    }
    return nil;
}

- (id)reload
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        [(UIWebView *)self.webView reload];
        return nil;
    } else if ([self.webView isKindOfClass:[WKWebView class]]) {
        return [(WKWebView *)self.webView reload];
    }
    return nil;
}

- (id)reloadFromOrigin
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        [(UIWebView *)self.webView reload];
        if (self.originRequest) {
            [self evaluateJavaScript:[NSString stringWithFormat:@"window.location.replace('%@')", self.originRequest.URL.absoluteString] completionHandler:nil];
        }
        return nil;
    } else if ([self.webView isKindOfClass:[WKWebView class]]) {
        return [(WKWebView *)self.webView reloadFromOrigin];
    }
    return nil;
}

- (void)stopLoading
{
    if ([self.webView isKindOfClass:UIWebView.class]) {
        [(UIWebView *)self.webView stopLoading];
    } else if ([self.webView isKindOfClass:WKWebView.class]) {
        [(WKWebView *)self.webView stopLoading];
    }
}

- (BOOL)scalesPageToFit
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        _scalesPageToFit = [(UIWebView *)self.webView scalesPageToFit];
    }
    return _scalesPageToFit;
}

- (void)setScalesPageToFit:(BOOL)scalesPageToFit
{
    if ([self.webView isKindOfClass:[UIWebView class]]) {
        [(UIWebView *)self.webView setScalesPageToFit:scalesPageToFit];
    }
    _scalesPageToFit = scalesPageToFit;
}

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler
{
    if ([self.webView isKindOfClass:UIWebView.class]) {
        [self.webViewEngine evaluateJavaScript:javaScriptString completionHandler:completionHandler];
    } else if ([self.webView isKindOfClass:WKWebView.class]) {
        [((WKWebView *)self.webView) evaluateJavaScript:javaScriptString completionHandler:completionHandler];
    }
}

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)javaScriptString
{
    if ([self.webView isKindOfClass:UIWebView.class]) {
        NSString *result = [(UIWebView *)self.webView stringByEvaluatingJavaScriptFromString:javaScriptString];
        return result;
    } else if ([self.webView isKindOfClass:WKWebView.class]) {
        __block NSString *result = nil;
        __block BOOL isExecuted = NO;
        [(WKWebView*)self.webView evaluateJavaScript:javaScriptString completionHandler:^(id obj, NSError* error) {
            result = obj;
            isExecuted = YES;
        }];
        
        while (isExecuted == NO) {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
        return result;
    }
    return nil;
}

- (void)yh_setScrollEnabled:(BOOL)enabled
{
    UIView *view = self.webView;
    UIScrollView *scrollView = view.scrollView;
    
    scrollView.scrollEnabled = enabled;
    scrollView.panGestureRecognizer.enabled = enabled;
    
    // There is one subview as of iOS 8.1 of class WKScrollView
    for (UIView* subview in view.subviews) {
        if ([subview respondsToSelector:@selector(setScrollEnabled:)]) {
            [(id)subview setScrollEnabled:enabled];
        }
        
        if ([subview respondsToSelector:@selector(panGestureRecognizer)]) {
            [[(id)subview panGestureRecognizer] setEnabled:enabled];
        }
        
        // here comes the tricky part, desabling
        for (UIView* subScrollView in subview.subviews) {
            if ([subScrollView isKindOfClass:NSClassFromString(@"UIWebBrowserView")]) {
                for (UIGestureRecognizer *gesture in [subScrollView gestureRecognizers]) {
                    if ([gesture isKindOfClass:NSClassFromString(@"UIWebTouchEventsGestureRecognizer")])
                        [gesture setEnabled:enabled];
                }
            }
        }
    }
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"title"])
    {
        NSString *title = change[NSKeyValueChangeNewKey];
        _pageTitle = title;
        if (self.delegate && [self.delegate respondsToSelector:@selector(pageTitleUpdated:)]) {
            [self.delegate pageTitleUpdated:title];
        }
    }
}

#pragma mark - CDVYHInterfaceDelegate
- (BOOL)parseLink:(NSString *)linkUrl
{
    for (id <YHLinkParserDelegate> parser in self.linkParsers) {
        if ([parser parseString:linkUrl]) {
            return YES;
        }
    }
    
    return NO;
}

- (void)nativeActionDidTriggerEventWithUserInfo:(NSDictionary *)userInfo completion:(void (^)(id, BOOL))completion {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self.delegate respondsToSelector:@selector(didGetMessageFromWeb:completion:)]) {
            [self.delegate didGetMessageFromWeb:userInfo completion:completion];
        }
    });
}

#pragma mark - Method Forwarding
- (BOOL)respondsToSelector:(SEL)aSelector
{
    if ([super respondsToSelector:aSelector]) {
        return YES;
    }
    
    if ([self.webView respondsToSelector:aSelector]) {
        return YES;
    }
    
    return NO;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
    if (!signature) {
        if (self.webView && [self.webView respondsToSelector:aSelector]) {
            return [(NSObject *)self.webView methodSignatureForSelector:aSelector];
        }
    }
    
    return signature;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    if (self.webView && [self.webView respondsToSelector:[anInvocation selector]]) {
        [anInvocation invokeWithTarget:self.webView];
    }
}

@end


@implementation YHExplorerCommandDelegate

#pragma mark CDVCommandDelegate implementation

- (id)getCommandInstance:(NSString*)className
{
    return [super getCommandInstance:className];
}

- (NSString*)pathForResource:(NSString*)resourcepath
{
    return [super pathForResource:resourcepath];
}

@end

@implementation YHExplorerCommandQueue

- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
    return [super execute:command];
}

@end