forked from illusionspaces/WKJavaScriptBridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSHRMCommandImpl.m
More file actions
86 lines (73 loc) · 2.59 KB
/
Copy pathSHRMCommandImpl.m
File metadata and controls
86 lines (73 loc) · 2.59 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
//
// SHRMCommandImpl.m
// Hybrid-framework
//
// Created by Kevin on 2019/4/20.
// Copyright © 2019 王凯. All rights reserved.
//
#import "SHRMCommandImpl.h"
#import "SHRMWebViewEngine.h"
#import "SHRMPluginResult.h"
@implementation SHRMCommandImpl {
__weak SHRMWebViewEngine *_webViewEngine;
NSRegularExpression* _callbackIdPattern;
}
- (instancetype)initWithWebViewEngine:(SHRMWebViewEngine *)webViewEngine {
if (self = [super init]) {
_webViewEngine = webViewEngine;
NSError* err = nil;
_callbackIdPattern = [NSRegularExpression regularExpressionWithPattern:@"[^A-Za-z0-9._-]" options:0 error:&err];
if (err != nil) {
// Couldn't initialize Regex
NSLog(@"Error: Couldn't initialize regex");
_callbackIdPattern = nil;
}
}
return self;
}
- (void)sendPluginResult:(SHRMPluginResult *)result callbackId:(NSString*)callbackId {
NSLog(@"Exec(%@): Sending result. Status=%@", callbackId, result.status);
// 当本次交互JS侧没有回调时
if ([@"INVALID" isEqualToString:callbackId]) {
return;
}
// 回调id格式不正确
if (![self isValidCallbackId:callbackId]) {
NSLog(@"Invalid callback id received by sendPluginResult");
return;
}
int status = [result.status intValue];
NSString* argumentsAsJSON = [result argumentsAsJSON];
NSString* js = [NSString stringWithFormat:@"fetchComplete('(%@)',%d,%@)", callbackId, status, argumentsAsJSON];
if (![NSThread isMainThread]) {
//不使用GCD是防止js页面死锁产生卡死
[self performSelectorOnMainThread:@selector(evalJs:) withObject:js waitUntilDone:NO];
} else {
[self evalJs:js];
}
}
- (void)evalJs:(NSString *)js {
[_webViewEngine.bridge evaluateJavaScript:js completionHandler:^(id obj, NSError * error) {
if (error) {
NSLog(@"evaluateJSError:%@",error.localizedDescription);
}
}];
}
- (id)getCommandInstance:(NSString*)pluginName {
return [_webViewEngine getCommandInstance:pluginName];
}
- (void)runInBackground:(void (^)(void))block {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);
}
- (BOOL)isValidCallbackId:(NSString*)callbackId
{
if ((callbackId == nil) || (_callbackIdPattern == nil)) {
return NO;
}
// 如果太长或发现任何无效字符,则禁用
if (([callbackId length] > 100) || [_callbackIdPattern firstMatchInString:callbackId options:0 range:NSMakeRange(0, [callbackId length])]) {
return NO;
}
return YES;
}
@end