IOS 中的JS
文章摘自: http://www.cocoachina.com/ios/20150127/11037.html
JSContext/JSValue
JSContext 即JavaScript代码的运行环境。一个Context就是一个JavaScript代码执行的环境,也叫作用域。当在浏览器中运行 JavaScript代码时,JSContext就相当于一个窗口,能轻松执行创建变量、运算乃至定义函数等的JavaScript
//Objective-CJSContext *context = [[JSContext alloc] init];[context evaluateScript:@"var num = 8 + 5"];[context evaluateScript:@"var names = ['Grace', 'Ada', 'Margaret']"];[context evaluateScript:@"var triple = function(value) { return value * 3 }"];JSValue *tripleNum = [context evaluateScript:@"triple(num)"];NSLog(@"Tripled: %d", [tripleNum toInt32]); //Swiftlet context = JSContext()context.evaluateScript("var num = 5 + 5")context.evaluateScript("var names = ['Grace', 'Ada', 'Margaret']")context.evaluateScript("var triple = function(value) { return value * 3 }")let tripleNum: JSValue = context.evaluateScript("triple(num)")println("Tripled: \(tripleNum.toInt32())")
JSValue *names = context[@"names"];JSValue *initialName = names[0];NSLog(@"The first name: %@", [initialName toString]);//Swiftlet names = context.objectForKeyedSubscript("names")let initialName = names.objectAtIndexedSubscript(0)println("The first name: \(initialName.toString())")//Objective-CJSValue *tripleFunction = context[@"triple"];JSValue *result = [tripleFunction callWithArguments:@[@5] ];NSLog(@"Five tripled: %d", [result toInt32]);//Swiftlet tripleFunction = context.objectForKeyedSubscript("triple")let result = tripleFunction.callWithArguments([5])println("Five tripled: \(result.toInt32())")//Objective-Ccontext.exceptionHandler = ^(JSContext *context, JSValue *exception) { NSLog(@"JS Error: %@", exception);};[context evaluateScript:@"function multiply(value1, value2) { return value1 * value2 "];// JS Error: SyntaxError: Unexpected end of script//Swiftcontext.exceptionHandler = { context, exception in println("JS Error: \(exception)")}context.evaluateScript("function multiply(value1, value2) { return value1 * value2 ")// JS Error: SyntaxError: Unexpected end of scriptJavaScript函数调用
了 解了从JavaScript环境中获取不同值以及调用函数的方法,那么反过来,如何在JavaScript环境中获取Objective-C或者 Swift定义的自定义对象和方法呢?要从JSContext中获取本地客户端代码,主要有两种途径,分别为Blocks和JSExport协议。
Blocks (块)
在JSContext中,如果Objective-C代码块赋值为一个标识 符,JavaScriptCore就会自动将其封装在JavaScript函数中,因而在JavaScript上使用Foundation和Cocoa类 就更方便些——这再次验证了JavaScriptCore强大的衔接作用。现在CFStringTransform也能在JavaScript上使用了, 如下所示:
//Objective-Ccontext[@"simplifyString"] = ^(NSString *input) { NSMutableString *mutableString = [input mutableCopy]; CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, NO); CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformStripCombiningMarks, NO); return mutableString;};NSLog(@"%@", [context evaluateScript:@"simplifyString('?????!')"]);//Swiftlet simplifyString: @objc_block String -> String = { input in var mutableString = NSMutableString(string: input) as CFMutableStringRef CFStringTransform(mutableString, nil, kCFStringTransformToLatin, Boolean(0)) CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Boolean(0)) return mutableString}context.setObject(unsafeBitCast(simplifyString, AnyObject.self), forKeyedSubscript: "simplifyString")println(context.evaluateScript("simplifyString('?????!')"))// annyeonghasaeyo!内存管理(Memory Management)
代码块可以捕获变量引用,而JSContext 所有变量的强引用都保留在JSContext中,所以要注意避免循环强引用问题。另外,也不要在代码块中捕获JSContext或任何JSValues, 建议使用[JSContext currentContext]来获取当前的Context对象,根据具体需求将值当做参数传入block中。
JSExport协议
借助JSExport协议也可以在JavaScript上使用自定义对象。在JSExport协议中声明的实例方法、类方法,不论属性,都能自动与JavaScrip交互。文章稍后将介绍具体的实践过程。
JavaScriptCore实践
我们可以通过一些例子更好地了解上述技巧的使用方法。先定义一 个遵循JSExport子协议PersonJSExport的Person model,再用JavaScript在JSON中创建和填入实例。有整个JVM,还要NSJSONSerialization干什么?
PersonJSExports和Person
Person类执行的 PersonJSExports协议具体规定了可用的JavaScript属性。,在创建时,类方法必不可少,因为JavaScriptCore并不适用 于初始化转换,我们不能像对待原生的JavaScript类型那样使用var person = new Person()。
//Objective-C// in Person.h -----------------@class Person;@protocol PersonJSExports @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; @property NSInteger ageToday; - (NSString *)getFullName; // create and return a new Person instance with `firstName` and `lastName` + (instancetype)createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;@end@interface Person : NSObject @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; @property NSInteger ageToday;@end// in Person.m -----------------@implementation Person- (NSString *)getFullName { return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];}+ (instancetype) createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName { Person *person = [[Person alloc] init]; person.firstName = firstName; person.lastName = lastName; return person;}@end//Swift// Custom protocol must be declared with `@objc`@objc protocol PersonJSExports : JSExport { var firstName: String { get set } var lastName: String { get set } var birthYear: NSNumber? { get set } func getFullName() -> String /// create and return a new Person instance with `firstName` and `lastName` class func createWithFirstName(firstName: String, lastName: String) -> Person}// Custom class must inherit from `NSObject`@objc class Person : NSObject, PersonJSExports { // properties must be declared as `dynamic` dynamic var firstName: String dynamic var lastName: String dynamic var birthYear: NSNumber? init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } class func createWithFirstName(firstName: String, lastName: String) -> Person { return Person(firstName: firstName, lastName: lastName) } func getFullName() -> String { return "\(firstName) \(lastName)" }}配置JSContext
创建Person类之后,需要先将其导出到JavaScript环境中去,同时还需导入Mustache JS库,以便对Person对象应用模板。
//Objective-C// export Person classcontext[@"Person"] = [Person class];// load Mustache.jsNSString *mustacheJSString = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];[context evaluateScript:mustacheJSString];//Swift// export Person classcontext.setObject(Person.self, forKeyedSubscript: "Person")// load Mustache.jsif let mustacheJSString = String(contentsOfFile:..., encoding:NSUTF8StringEncoding, error:nil) { context.evaluateScript(mustacheJSString)}JavaScript数据&处理
以下简单列出一个JSON范例,以及用JSON来创建新Person实例。
注 意:JavaScriptCore实现了Objective-C/Swift的方法名和JavaScript代码交互。因为JavaScript没有命名 好的参数,任何额外的参数名称都采取驼峰命名法(Camel-Case),并附加到函数名称上。在此示例中,Objective-C的方法 createWithFirstName:lastName:在JavaScript中则变成了 createWithFirstNameLastName()。
//JSON[ { "first": "Grace", "last": "Hopper", "year": 1906 }, { "first": "Ada", "last": "Lovelace", "year": 1815 }, { "first": "Margaret", "last": "Hamilton", "year": 1936 }]//JavaScriptvar loadPeopleFromJSON = function(jsonString) { var data = JSON.parse(jsonString); var people = []; for (i = 0; i < data.length; i++) { var person = Person.createWithFirstNameLastName(data[i].first, data[i].last); person.birthYear = data[i].year; people.push(person); } return people;}//Objective-C// get JSON stringNSString *peopleJSON = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];// get load functionJSValue *load = context[@"loadPeopleFromJSON"];// call with JSON and convert to an NSArrayJSValue *loadResult = [load callWithArguments:@[peopleJSON]];NSArray *people = [loadResult toArray];// get rendering function and create templateJSValue *mustacheRender = context[@"Mustache"][@"render"];NSString *template = @"{{getFullName}}, born {{birthYear}}";// loop through people and render Person object as stringfor (Person *person in people) { NSLog(@"%@", [mustacheRender callWithArguments:@[template, person]]);}// Output:// Grace Hopper, born 1906// Ada Lovelace, born 1815//Swift// get JSON stringif let peopleJSON = NSString(contentsOfFile:..., encoding: NSUTF8StringEncoding, error: nil) { // get load function let load = context.objectForKeyedSubscript("loadPeopleFromJSON") // call with JSON and convert to an array of `Person` if let people = load.callWithArguments([peopleJSON]).toArray() as? [Person] { // get rendering function and create template let mustacheRender = context.objectForKeyedSubscript("Mustache").objectForKeyedSubscript("render") let template = "{{getFullName}}, born {{birthYear}}" // loop through people and render Person object as string for person in people { println(mustacheRender.callWithArguments([template, person])) } }}// Output:// Grace Hopper, born 1906// Ada Lovelace, born 1815// Margaret Hamilton, born 1936IOS 中的JS的更多相关文章
- 一些在IOS中关于JS、H5开发的网站
1.JSPatch 2.
- iOS中JS 与OC的交互(JavaScriptCore.framework)
iOS中实现js与oc的交互,目前网上也有不少流行的开源解决方案: 如:react native 当然一些轻量级的任务使用系统提供的UIWebView 以及JavaScriptCore.framewo ...
- ios开发--网页中调用JS与JS注入
先将网页弄到iOS项目中: 网页内容如下, 仅供测试: <html> <head> <meta xmlns="http://www.w3.org/1999/xh ...
- 【iOS】网页中调用JS与JS注入
非常多应用为了节约成本,做出同一时候在Android与iOS上都能使用的界面,这时就要使用WebView来做.Android和IOS上都有WebView,做起来非常省事.当然这时就要考虑怎样在Andr ...
- iOS中使用UIWebView与JS进行交互
iOS中使用UIWebView与JS进行交互 前一段忙着面试和复习,这两天终于考完试了,下学期的实习也有了着落,把最近学的东西更新一下,首先是使用UIWebView与JS进行交互 在webView中我 ...
- iOS中UIWebView使用JS交互 - 机智的新手
iOS中偶尔也会用到webview来显示一些内容,比如新闻,或者一段介绍.但是用的不多,现在来教大家怎么使用js跟webview进行交互. 这里就拿点击图片获取图片路径为例: 1.测试页面html & ...
- iOS中UIWebView执行JS代码(UIWebView)
iOS中UIWebView执行JS代码(UIWebView) 有时候iOS开发过程中使用 UIWebView 经常需要加载网页,但是网页中有很多明显的标记让人一眼就能看出来是加载的网页,而我们又不想被 ...
- JS 解决 IOS 中拍照图片预览旋转 90度 BUG
上篇博文[ Js利用Canvas实现图片压缩 ]中做了图片压缩上传,但是在IOS真机测试的时候,发现图片预览的时候自动逆时针旋转了90度.对于这个bug,我完全不知道问题出在哪里,接下来就是面向百度编 ...
- iOS中js与objective-c的交互(转)
因为在iOS中没有WebKit.Framework这个库的,所以也就没有 windowScriptObject对象方法了.要是有这个的方法的话 就方便多了,(ps:MacOS中有貌似) 现在我们利用其 ...
随机推荐
- 【机器学习实战】Machine Learning in Action 代码 视频 项目案例
MachineLearning 欢迎任何人参与和完善:一个人可以走的很快,但是一群人却可以走的更远 Machine Learning in Action (机器学习实战) | ApacheCN(apa ...
- mariadb自带命令行客户端指令笔记
mysql -H 主机IP -u 用户名 -p -p表示要输密码,不要直接输了,要回车后在程序里输入 显示数据库列表: show databases; 选择XX数据库: use XX; 显示数据库里的 ...
- Ansible系列(六):循环和条件判断
本文目录:1. 循环 1.1 with_items迭代列表 1.2 with_dict迭代字典项 1.3 with_fileglob迭代文件 1.4 with_lines迭代行 1.5 with_ne ...
- js转换字符串为数值的方法
在js读取文本框或者其他表单数据的时候获得的值是字符串类型的,比如两个文本框a和b,假设获得a的value值为11,b的value值为9 ,那么a.value要小于b.value,由于他们都是字符串形 ...
- asp.net mvc项目实记-开启伪静态-Bundle压缩css,js
百度这些东西,还是会浪费了一些不必要的时间,记录记录以备后续 一.开启伪静态 如果不在web.config中配置管道开关则伪静态无效 首先在RouteConfig.cs中中注册路由 routes.Ma ...
- 深入理解String的关键点和方法
String是Java开发中最最常见的,本篇博客针对String的原理和常用的方法,以及String的在开发中常见问题做一个整体性的概括整理.因为之前对String的特性做过一些分析,所以不在详细描述 ...
- Message:Unable to locate element 问题解决方法
Python断断续续学了有一段时间了,总感觉不找个小项目练练手心里没底,哪成想出门就遇到"拦路虎",一个脚本刚写完就运行报错,还好做足了心里准备,尝试自行解决. 或许网上有相关解决 ...
- Windows 编程中恼人的各种字符以及字符指针类型
在Windows编程中,很容易见到这些数据类型:LPSTR,LPTSTR,LPCTSTR... 像很多童鞋一样,当初在学Windows编程的时候,对着些数据类型真的是丈二和尚,摸不着头脑,长时间不用就 ...
- 使用千位分隔符(逗号)表示web网页中的大数字
做手机端页面我们常常遇到数字,而在Safari浏览器下这些数字会默认显示电话号码,于是我们就用到了补坑的方法加入<meta>标签: <meta name="format-d ...
- java核心卷轴之泛型程序设计
本文根据<Java核心卷轴>第十二章总结而来,更加详细的内容请查看<Java核心卷轴> 1. 泛型类型只能是引用类型,不可以使用基本数据类型. 2. 类型变量含义 E : 集合 ...