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中有貌似) 现在我们利用其 ...
随机推荐
- js 第一课
什么是JavaScript JavaScript是一种脚本语言,运行在网页上.无需安装编译器.只要在网页浏览器上就能运行 一般JavaScript与HTML合作使用. 例如 <html> ...
- 谈一谈synchronized关键词
1.使用 java中的每一个对象都可以作为synchronized的锁进行代码同步,常见的形式 同步代码块锁是synchronized括号内的对象 普通成员方法上,锁是当前的对象,synchroniz ...
- Flask-WTF 创建表单P2
表单安全 无需任何配置,FlaskForm将提供具有CSRF(Cross-site request forgery,也被称为one-click attack 或者session riding,通常缩写 ...
- 绘制QQ圆形图像
思路:这里用到的是图像求交.现在画布上画上圆形,即所需要的圆形头像,然后设置paint的属性设置为求交集,再将bitmap划到canvas上面就好了. 代码如下: private static Bit ...
- Java伪代码描述《大道至简》第一章
第一节 Begin //原始需求 惩山北之塞,出入之迂 //项目沟通的基本方式 聚室而谋曰 //项目目标 毕力平险,指通豫南,达于汉阴 //技术方案 扣石垦壤,箕畚运于渤海之尾 //技术人员和工程管理 ...
- HIVE---基于Hadoop的数据仓库工具讲解
Hadoop: Hadoop是一个由Apache基金会所开发的分布式系统基础架构.用来开发分布式程序.充分利用集群的威力进行高速运算和存储.Hadoop实现了一个分布式文件系统(Hadoop Dist ...
- 简单Elixir游戏服设计-玩家进程注册
上回说用Registry 做本地注册(跨服可以用syn,只是稍微麻烦点,需要模拟global注册机制,写个封装模块). 修改game_server 项目的mix.exs, 增加应用启动 def app ...
- 记住密码"功能的正确设计
Web上的用户登录功能应该是最基本的功能了,可是在我看过一些站点的用户登录功能后,我觉得很有必要写一篇文章教大家怎么来做用户登录功能.下面的文章告诉大家这个功能可能并没有你所想像的那么简单,这是一个关 ...
- (原)怎样解决python dataframe loc,iloc循环处理速度很慢的问题
怎样解决python dataframe loc,iloc循环处理速度很慢的问题 1.问题说明 最近用DataFrame做大数据 处理,发现处理速度特别慢,追究原因,发现是循环处理时,loc,iloc ...
- ConvertUtils.register注册转换器
当用到BeanUtils的populate.copyProperties方法或者getProperty,setProperty方法其实都会调用convert进行转换 但Converter只支持一些基本 ...