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中有貌似) 现在我们利用其 ...
随机推荐
- iOS 信号量
信号量就是一个资源计数器,对信号量有两个操作来达到互斥,分别是P和V操作. 一般情况是这样进行临界访问或互斥访问的: 设信号量值为1, 当一个进程1运行是,使用资源,进行P操作,即对信号量值减1, ...
- 尝试在Linux上部署Asp.net Core应用程序
快两个月没接触.net,倒是天天在用Linux,所以想尝试一下在Linux运行喜欢的.net 应用. 安装CentOS 安装.Net core for Linux 创建Asp.net Core应用程序 ...
- xml跟sql查找
xml小白笔记 ....... <sql id="wDishesColumns"> a.id AS "id", a.pid AS "pid ...
- 深入理解计算机系统_3e 第二章家庭作业答案
初始完成者:哈尔滨工业大学 李秋豪 许可:除2.55对应代码外(如需使用请联系randy.bryant@cs.cmu.edu),任何人可以自由的使用,修改,分发本文档的代码. 本机环境: (有一些需要 ...
- jmeter3.3测试需要登录的接口(java)
1.新建线程组-略过 2.右键线程组->添加->配置元件->HTTP授权管理器 3.右键线程组->添加->配置元件->HTTP信息头管理器 4.右键线程组-> ...
- Css Html 大风车
<div style = "height:500px;width:500px;position:static;float:left;"><div class=&q ...
- VBA /VB/VB中合成分散数据方法
公司用于项目号的合成,怕忘记,特此放上这里.若能帮助其它道友,善莫大焉. 比如:001,004,006,007,008,009,010 结果可以输出:001,004,006-010 逻辑:1.获得数据 ...
- php Socket通信
<?php error_reporting(0); $host = "0.0.0.0"; $port = 1082; $maxUser = 10; set_time_limi ...
- webservice接口国内手机号码归属地查询
操作步骤: 1.打开eclipse,新建web工程MobileCodeClient 2.打开运行窗口 右击工程名选择properties 切换到运行窗口,按图切换到相应的目录里 执行命令: wsdl2 ...
- Linux上mysql的安装与配置
前言 在我们使用Linux的过程中,可能会使用到数据库.那么,数据库的安装与配置就是我们需要掌握的了~所以呢,这篇博客小编就来给大家唠唠数据库的安装与配置. 说到编译安装,小编脑海里浮现的第一个方法就 ...