YHExplorerViewController.m
12.9 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
//
// 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"
@interface YHExplorerViewController ()
@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.webView stopLoading];
self.webView.delegate = nil;
[self.webView removeFromSuperview];
self.progressBar = nil;
[self removeProgress];
self.progressView = nil;
self.webView = nil;
if ([[NSURLCache sharedURLCache] isKindOfClass:[YHURLCache class]]) {
YHURLCache *cache = (YHURLCache *)[YHURLCache sharedURLCache];
[cache removeUrlsForKey:self.pointerValue];
}
}
- (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];
}
}
- (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 = [[YHWebViewProgressView alloc]init];
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", nil];
}
return _autoSchemes;
}
- (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 *)url
{
self.startPage = url;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
if ([self.delegate respondsToSelector:@selector(explorerWillLoadRequest:)]) {
[self.delegate explorerWillLoadRequest:request];
}
[self.webView loadRequest:request];
}
- (void)loadHTMLString:(NSString *)html
{
[self.webView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}
- (void)loadHTMLString:(NSString *)html baseURL:(nullable NSURL *)baseURL
{
[self.webView 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
/**
* 动态注入Js
*
* @param resource js的名称
*/
- (BOOL)injectJavascript:(NSString *)resource {
NSString *jsPath = [[NSBundle mainBundle] pathForResource:resource ofType:@"js"];
NSString *js = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:NULL];
return ([self.webView stringByEvaluatingJavaScriptFromString:js] != nil);
}
/**
@brief 循环注入直到成功
@since 1.0.2
*/
- (void)cycleInject {
BOOL bSuc = NO;
// 向网页中注入cordova
bSuc = [self injectJavascript:@"cordova"];
if (!bSuc) {
__weak typeof(self) weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf cycleInject];
});
}
}
- (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)webViewDidFinishLoad:(UIWebView*)theWebView
{
NSString *title = [theWebView stringByEvaluatingJavaScriptFromString: @"document.title"];
_pageTitle = title;
if (self.delegate && [self.delegate respondsToSelector:@selector(pageTitleUpdated:)]) {
[self.delegate pageTitleUpdated:title];
}
[super webViewDidFinishLoad:theWebView];
[self cycleInject];
if (self.delegate && [self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
[self.delegate webViewDidFinishLoad:theWebView];
}
if (self.progressBar) {
[self.progressBar webViewDidFinishLoad:theWebView];
}
NSString *key = [[NSString alloc] initWithFormat:@"WebKit%@%@", @"CacheModel", @"PreferenceKey"];//WebKitCacheModelPreferenceKey
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void) webViewDidStartLoad:(UIWebView*)theWebView
{
[super webViewDidStartLoad:theWebView];
if (self.delegate && [self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
[self.delegate webViewDidStartLoad:theWebView];
}
if (self.progressBar) {
[self.progressBar webViewDidStartLoad:theWebView];
}
[self cycleInject];
}
- (void) webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
{
[super webView:theWebView didFailLoadWithError:error];
if (self.delegate && [self.delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
[self.delegate webView:theWebView didFailLoadWithError:error];
}
if (self.progressBar) {
[self.progressBar webView:theWebView didFailLoadWithError:error];
}
}
- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
if (self.progressBar && [self.progressBar checkIfRPCURL:request]) {
return NO;
}
if ([self.delegate respondsToSelector:@selector(webView:didCatchRequest:navigationType:)]) {
[self.delegate webView:theWebView didCatchRequest:request navigationType:navigationType];
}
BOOL b = [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
if (self.delegate && [self.delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
b = [self.delegate webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
}
if (self.progressBar && b) {
b = [self.progressBar webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
}
if (self.automaticallySchemeHandle && b) {
if ([[UIApplication sharedApplication] canOpenURL:request.URL]) {
NSArray *array = [self.autoSchemes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", request.URL.scheme]];
if (array.count > 0) {
[[UIApplication sharedApplication] openURL:request.URL];
}
}
}
// 尝试把当前url添加至缓存
if (b && [[request.URL scheme] hasPrefix:@"http"] && [[NSURLCache sharedURLCache] isKindOfClass:[YHURLCache class]]) {
YHURLCache *cache = (YHURLCache *)[YHURLCache sharedURLCache];
[cache addCacheUrl:request.URL.absoluteString forKey:self.pointerValue];
}
return b;
}
#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