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中有貌似) 现在我们利用其 ...
随机推荐
- Java Map对象的遍历
一般情况下Map的实现类中用的最多的是 HashMap . Map的遍历也就是迭代 1. 在for-each循环中使用entries来遍历 (既要取键,又要取值) Map<String, St ...
- 嵌入系统squashfs挂载常见问题总结
由于squahsfs的一些优点,嵌入系统常常直接使用squashfs作为initrd挂载到/dev/ram,作为rootfs.这里对常见的一些问题进行一些分析. 1. kernel启动出现错误 RAM ...
- GUI PasswordField
GUI.PasswordField public static function PasswordField(position: Rect, password: string, maskChar: c ...
- stl 和并查集应用
抱歉这么久才写出一篇文章,最近进度有点慢.这么慢是有原因的,我在想如何改进能让大家看系列文章的时候更方便一些,现在这个问题有了答案,在以后的推送中,我将尽量把例题和相关知识点在同一天推出,其次在代码分 ...
- MyBatis框架(三)动态SQL,分页,二进制存入数据库图片
一.动态sql语句,分页 1, <if>条件 <if test="key!=null"> 拼接sql语句 </if> 2, <choose ...
- .NET 动态脚本语言
Script.NET (S#) 是一种允许为你的应用程序自定义行为,与本地.NET对象.类型和组件交互动态的脚本语言.托管应用程序本身可以改变一个xml配置脚本运行时的默认行为,更换绑定的方法,属性, ...
- 面试题之-----String,StringBuffer,StringBuilder的区别
String :字符串常量,值不能改变. String s="abc"; s=s+"def"; System.out.println(s); 输出结果为: ab ...
- InnoDB Undo Log
简介 Undo Log包含了一系列在一个单独的事务中会产生的所有Undo Log记录.每一个Undo Log记录包含了如何undo事务对某一行修改的必要信息.InnoDB使用Undo Log来进行事务 ...
- NOIP2017SummerTraining0714
个人感受:第一题做了字典树,还运行错误,然后就弃疗了,然后水了二三两题,总共拿了85分,倒数. 正确答案 时间限制: 2 Sec 内存限制: 256 MB提交: 702 解决: 82[提交][状态 ...
- 偏置-方差分解(Bias-Variance Decomposition)
本文地址为:http://www.cnblogs.com/kemaswill/,作者联系方式为kemaswill@163.com,转载请注明出处. 机器学习的目标是学得一个泛化能力比较好的模型.所谓泛 ...