Skip to content

Commit

Permalink
引入JavaScriptCore实例
Browse files Browse the repository at this point in the history
  • Loading branch information
wujunyang committed Oct 8, 2016
1 parent 44c7164 commit 4262461
Show file tree
Hide file tree
Showing 11 changed files with 834 additions and 467 deletions.
948 changes: 491 additions & 457 deletions MobileProject.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

32 changes: 26 additions & 6 deletions MobileProject/Assets.xcassets/AppIcon.appiconset/Contents.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
Expand Down Expand Up @@ -54,6 +64,16 @@
"filename" : "icon-60@3x.png",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
Expand Down Expand Up @@ -114,6 +134,12 @@
"filename" : "icon-76@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "icon-83.5@2x.png",
"scale" : "2x"
},
{
"size" : "24x24",
"idiom" : "watch",
Expand Down Expand Up @@ -167,12 +193,6 @@
"scale" : "2x",
"role" : "quickLook",
"subtype" : "42mm"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "icon-83.5@2x.png",
"scale" : "2x"
}
],
"info" : {
Expand Down
2 changes: 1 addition & 1 deletion MobileProject/Expand/Tool/JSPatchHelper/JSPatchHelper.m
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ +(void)loadJSPatch
if (!BBUserDefault.MBJsPatchTime) {
BBUserDefault.MBJsPatchTime=myNowDate;
}

NSLog(@"%@",BBUserDefault.MBJsPatchTime);
if ([myNowDate timeIntervalSinceDate:BBUserDefault.MBJsPatchTime]<3600) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//
// MPJavaScriptCoreViewController.h
// MobileProject
//
// Created by wujunyang on 16/10/8.
// Copyright © 2016年 wujunyang. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "BaseViewController.h"
#import "MPJavaScriptModel.h"

@interface MPJavaScriptCoreViewController : BaseViewController<UIWebViewDelegate>

@end
120 changes: 120 additions & 0 deletions MobileProject/Main/Preview/Controller/MPJavaScriptCoreViewController.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
//
// MPJavaScriptCoreViewController.m
// MobileProject
//
// Created by wujunyang on 16/10/8.
// Copyright © 2016年 wujunyang. All rights reserved.
//

#import "MPJavaScriptCoreViewController.h"

@interface MPJavaScriptCoreViewController ()

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) JSContext *jsContext;

@end

@implementation MPJavaScriptCoreViewController

- (void)viewDidLoad {
[super viewDidLoad];

self.view.backgroundColor=[UIColor grayColor];

[self.view addSubview:self.webView];

// // 一个JSContext对象,就类似于Js中的window,只需要创建一次即可。
// self.jsContext = [[JSContext alloc] init];
//
// // jscontext可以直接执行JS代码。
// [self.jsContext evaluateScript:@"var num = 10"];
// [self.jsContext evaluateScript:@"var squareFunc = function(value) { return value * 2 }"];
// // 计算正方形的面积
// JSValue *square = [self.jsContext evaluateScript:@"squareFunc(num)"];
//
// // 也可以通过下标的方式获取到方法
// JSValue *squareFunc = self.jsContext[@"squareFunc"];
// JSValue *value = [squareFunc callWithArguments:@[@"20"]];
// NSLog(@"%@", square.toNumber);
// NSLog(@"%@", value.toNumber);
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}


#pragma mark 重写BaseViewController设置内容

//设置导航栏背景色
-(UIColor*)set_colorBackground
{
return [UIColor whiteColor];
}

////设置标题
-(NSMutableAttributedString*)setTitle
{
return [self changeTitle:@"JavaScriptCore运用"];
}

//设置左边按键
-(UIButton*)set_leftButton
{
UIButton *left_button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
[left_button setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateNormal];
[left_button setImage:[UIImage imageNamed:@"nav_back"] forState:UIControlStateHighlighted];
return left_button;
}

//设置左边事件
-(void)left_button_event:(UIButton*)sender
{
[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 通过模型调用方法,这种方式更好些。
MPJavaScriptModel *model = [[MPJavaScriptModel alloc] init];
self.jsContext[@"OCModel"] = model;
model.jsContext = self.jsContext;
model.webView = self.webView;

self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
}

- (void)webViewDidStartLoad:(UIWebView *)webView {

}

#pragma mark 自定义代码

-(NSMutableAttributedString *)changeTitle:(NSString *)curTitle
{
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:curTitle];
[title addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x333333) range:NSMakeRange(0, title.length)];
[title addAttribute:NSFontAttributeName value:CHINESE_SYSTEM(18) range:NSMakeRange(0, title.length)];
return title;
}

- (UIWebView *)webView {
if (_webView == nil) {
_webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
_webView.scalesPageToFit = YES;
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
_webView.delegate = self;
}

return _webView;
}

@end
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#import "MPYYTextViewController.h"
#import "MPExpandHideViewController.h"
#import "MPFormViewController.h"
#import "MPJavaScriptCoreViewController.h"

@interface MPMoreViewController : BaseViewController

Expand Down
12 changes: 9 additions & 3 deletions MobileProject/Main/Preview/Controller/MPMoreViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ - (void)viewDidLoad {
self.navigationItem.title=@"功能导航";

if (!self.dataArray) {
self.dataArray=@[@"JSPatch热更新",@"LKDB数据库运用",@"百度地图",@"二维码",@"照片上传",@"照片上传附带进度",@"字体适配机型",@"日志记录",@"列表倒计时",@"H5交互WebViewJavascriptBridge",@"继承BaseViewController运用",@"列表空白页展现",@"省市区三级联动",@"自定义弹出窗",@"YYText富文本实例",@"列表行展开跟回收隐藏",@"常见表单行类型" ,@"人脸识别注册及验证"];
self.dataArray=@[@"JSPatch热更新",@"LKDB数据库运用",@"百度地图",@"二维码",@"照片上传",@"照片上传附带进度",@"字体适配机型",@"日志记录",@"列表倒计时",@"H5交互WebViewJavascriptBridge",@"继承BaseViewController运用",@"列表空白页展现",@"省市区三级联动",@"自定义弹出窗",@"YYText富文本实例",@"列表行展开跟回收隐藏",@"常见表单行类型" ,@"人脸识别注册及验证",@"JavaScriptCore运用"];
}

//弹出提示
Expand Down Expand Up @@ -184,6 +184,12 @@ - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
{
[self.navigationController pushViewController:[NSClassFromString(@"FaceRecognitionController") new] animated:YES];
break;
}
case 18:
{
MPJavaScriptCoreViewController *vc=[[MPJavaScriptCoreViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
break;
}
default:
break;
Expand All @@ -193,15 +199,15 @@ - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath

#pragma mark 自定义代码

- (void)showNewStatusesCount:(int)count
- (void)showNewStatusesCount:(NSInteger)count
{
// 1.创建一个UILabel
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:12];

// 2.显示文字
if (count) {
label.text = [NSString stringWithFormat:@"共有%d条实例数据", count];
label.text = [NSString stringWithFormat:@"共有%ld条实例数据", count];
} else {
label.text = @"没有最新的数据";
}
Expand Down
33 changes: 33 additions & 0 deletions MobileProject/Main/Preview/Model/MPJavaScriptModel.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//
// MPJavaScriptModel.h
// MobileProject
//
// Created by wujunyang on 16/10/8.
// Copyright © 2016年 wujunyang. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>


@protocol JavaScriptObjectiveCDelegate <JSExport>

// JS调用此方法来调用OC的系统相册方法
- (void)callSystemCamera;
// 在JS中调用时,函数名应该为showAlertMsg(arg1, arg2)
// 这里是只两个参数的。
- (void)showAlert:(NSString *)title msg:(NSString *)msg;
// 通过JSON传过来
- (void)callWithDict:(NSDictionary *)params;
// JS调用Oc,然后在OC中通过调用JS方法来传值给JS。
- (void)jsCallObjcAndObjcCallJsWithDict:(NSDictionary *)params;

@end


@interface MPJavaScriptModel : NSObject<JavaScriptObjectiveCDelegate>

@property (nonatomic, weak) JSContext *jsContext;
@property (nonatomic, weak) UIWebView *webView;

@end
42 changes: 42 additions & 0 deletions MobileProject/Main/Preview/Model/MPJavaScriptModel.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//
// MPJavaScriptModel.m
// MobileProject
//
// Created by wujunyang on 16/10/8.
// Copyright © 2016年 wujunyang. All rights reserved.
//

#import "MPJavaScriptModel.h"

@implementation MPJavaScriptModel

- (void)callWithDict:(NSDictionary *)params {
NSLog(@"Js调用了OC的方法,参数为:%@", params);
}

// Js调用了callSystemCamera
- (void)callSystemCamera {
NSLog(@"JS调用了OC的方法,调起系统相册");

// JS调用后OC后,又通过OC调用JS,但是这个是没有传参数的
JSValue *jsFunc = self.jsContext[@"jsFunc"];
[jsFunc callWithArguments:nil];
}

- (void)jsCallObjcAndObjcCallJsWithDict:(NSDictionary *)params {
NSLog(@"jsCallObjcAndObjcCallJsWithDict was called, params is %@", params);

// 调用JS的方法
JSValue *jsParamFunc = self.jsContext[@"jsParamFunc"];
[jsParamFunc callWithArguments:@[@{@"age": @10, @"name": @"lili", @"height": @158}]];
}

- (void)showAlert:(NSString *)title msg:(NSString *)msg {
//JS都是在子线程里面,要调用主线程来执行UI动作
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *a = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[a show];
});
}

@end
47 changes: 47 additions & 0 deletions MobileProject/Resource/JsHtmlCss/test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<title>测试IOS与JS之前的互调</title>
<style type="text/css">
* {
font-size: 40px;
}
</style>
<script type="text/javascript">

var jsFunc = function() {
alert('Objective-C call js to show alert');
}

var jsParamFunc = function(argument) {
document.getElementById('jsParamFuncSpan').innerHTML
= argument['name'];
}

</script>

</head>

<body>

<div style="margin-top: 100px">
<h1>Test how to use objective-c call js</h1>
<input type="button" value="Call ObjC system camera" onclick="OCModel.callSystemCamera()">
<input type="button" value="Call ObjC system alert" onclick="OCModel.showAlertMsg('js title', 'js message')">
</div>

<div>
<input type="button" value="Call ObjC func with JSON " onclick="OCModel.callWithDict({'name': 'testname', 'age': 10, 'height': 170})">
<input type="button" value="Call ObjC func with JSON and ObjC call js func to pass args." onclick="OCModel.jsCallObjcAndObjcCallJsWithDict({'name': 'testname', 'age': 10, 'height': 170})">
</div>
<div>
<a href="test1.html">Click to next page</a>
</div>

<div>
<span id="jsParamFuncSpan" style="color: red; font-size: 50px;"></span>
</div>


</body>
</html>
Loading

0 comments on commit 4262461

Please sign in to comment.