在Swift中使用JavaScript的方法和技巧

移动开发 iOS
本文作者Nate Cook是一位独立的Web及移动应用开发者,是继Mattt大神之后NSHipster的主要维护者,也是非常知名活跃的Swift博主,并且还是支持自动生成Swift在线文档的SwiftDoc.org网站创造者。在本文中,他介绍了在Swift中使用JavaScript的方法和技巧,对于iOS和Web应用工程师有着非常实用的价值,以下为译文:

本文作者Nate Cook是一位独立的Web及移动应用开发者,是继Mattt大神之后NSHipster的主要维护者,也是非常知名活跃的Swift博主,并且还是支持自动生成Swift在线文档的SwiftDoc.org网站创造者。在本文中,他介绍了在Swift中使用JavaScript的方法和技巧,对于iOS和Web应用工程师有着非常实用的价值,以下为译文:

在RedMonk发布的2015年1月编程语言排行榜中,Swift采纳率排名迅速飙升,从刚刚面世时的68位跃至22位,Objective-C仍然稳居***0,而JavaScript则凭借着其在iOS平台上原生体验优势成为了年度最火热的编程语言。

[[132047]]

而早在2013年苹果发布的OS X Mavericks和iOS 7两大系统中便均已加入了JavaScriptCore框架,能够让开发者轻松、快捷、安全地使用JavaScript语言编写应用。不论叫好叫骂,JavaScript霸主地位已成事实。开发者们趋之若鹜,JS工具资源层出不穷,用于OS

X和iOS系统等高速虚拟机也蓬勃发展起来。

JSContext/JSValue

JSContext即JavaScript代码的运行环境。一个Context就是一个JavaScript代码执行的环境,也叫作用域。当在浏览器中运行JavaScript代码时,JSContext就相当于一个窗口,能轻松执行创建变量、运算乃至定义函数等的JavaScript代码:

  1. //Objective-C 
  2. JSContext *context = [[JSContext alloc] init]; 
  3. [context evaluateScript:@"var num = 5 + 5"]; 
  4. [context evaluateScript:@"var names = ['Grace', 'Ada', 'Margaret']"]; 
  5. [context evaluateScript:@"var triple = function(value) { return value * 3 }"]; 
  6. JSValue *tripleNum = [context evaluateScript:@"triple(num)"];
  1. //Swift 
  2. let context = JSContext() 
  3. context.evaluateScript("var num = 5 + 5"
  4. context.evaluateScript("var names = ['Grace', 'Ada', 'Margaret']"
  5. context.evaluateScript("var triple = function(value) { return value * 3 }"
  6. let tripleNum: JSValue = context.evaluateScript("triple(num)"

像JavaScript这类动态语言需要一个动态类型(Dynamic Type), 所以正如代码***一行所示,JSContext里不同的值均封装在JSValue对象中,包括字符串、数值、数组、函数等,甚至还有Error以及null和undefined。

JSValue包含了一系列用于获取Underlying Value的方法,如下表所示:

想要检索上述示例中的tripleNum值,只需使用相应的方法即可:

  1. //Objective-C 
  2. NSLog(@"Tripled: %d", [tripleNum toInt32]); 
  3. // Tripled: 30
  1. //Swift 
  2. println("Tripled: \(tripleNum.toInt32())"
  3. // Tripled: 30 

下标值(Subscripting Values)

通过在JSContext和JSValue实例中使用下标符号可以轻松获取上下文环境中已存在的值。其中,JSContext放入对象和数组的只能是字符串下标,而JSValue则可以是字符串或整数下标。

  1. //Objective-C 
  2. JSValue *names = context[@"names"]; 
  3. JSValue *initialName = names[0]; 
  4. NSLog(@"The first name: %@", [initialName toString]); 
  5. // The first name: Grace
  1. //Swift 
  2. let names = context.objectForKeyedSubscript("names"
  3. let initialName = names.objectAtIndexedSubscript(0
  4. println("The first name: \(initialName.toString())"
  5. // The first name: Grace 

而Swift语言毕竟才诞生不久,所以并不能像Objective-C那样自如地运用下标符号,目前,Swift的方法仅能实现objectAtKeyedSubscript()和objectAtIndexedSubscript()等下标。

函数调用(Calling Functions)

我们可以将Foundation类作为参数,从Objective-C/Swift代码上直接调用封装在JSValue的JavaScript函数。这里,JavaScriptCore再次发挥了衔接作用。

  1. //Objective-C 
  2. JSValue *tripleFunction = context[@"triple"]; 
  3. JSValue *result = [tripleFunction callWithArguments:@[@5] ]; 
  4. NSLog(@"Five tripled: %d", [result toInt32]);
  1. //Swift 
  2. let tripleFunction = context.objectForKeyedSubscript("triple"
  3. let result = tripleFunction.callWithArguments([5]) 
  4. println("Five tripled: \(result.toInt32())"

异常处理(Exception Handling)

JSContext还有一个独门绝技,就是通过设定上下文环境中exceptionHandler的属性,可以检查和记录语法、类型以及出现的运行时错误。exceptionHandler是一个回调处理程序,主要接收JSContext的reference,进行异常情况处理。

  1. //Objective-C 
  2. context.exceptionHandler = ^(JSContext *context, JSValue *exception) { 
  3.    NSLog(@"JS Error: %@", exception); 
  4. }; 
  5. [context evaluateScript:@"function multiply(value1, value2) { return value1 * value2 "]; 
  6. // JS Error: SyntaxError: Unexpected end of script 
  1. //Swift 
  2. context.exceptionHandler = { context, exception in 
  3.     println("JS Error: \(exception)"
  4. context.evaluateScript("function multiply(value1, value2) { return value1 * value2 "
  5. // JS Error: SyntaxError: Unexpected end of script 

JavaScript函数调用

了解了从JavaScript环境中获取不同值以及调用函数的方法,那么反过来,如何在JavaScript环境中获取Objective-C或者Swift定义的自定义对象和方法呢?要从JSContext中获取本地客户端代码,主要有两种途径,分别为Blocks和JSExport协议。

Blocks (块)

在JSContext中,如果Objective-C代码块赋值为一个标识符,JavaScriptCore就会自动将其封装在JavaScript函数中,因而在JavaScript上使用Foundation和Cocoa类就更方便些——这再次验证了JavaScriptCore强大的衔接作用。现在CFStringTransform也能在JavaScript上使用了,如下所示:

  1. //Objective-C 
  2. context[@"simplifyString"] = ^(NSString *input) { 
  3.    NSMutableString *mutableString = [input mutableCopy]; 
  4.    CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, NO); 
  5.    CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformStripCombiningMarks, NO); 
  6.    return mutableString; 
  7. }; 
  8. NSLog(@"%@", [context evaluateScript:@"simplifyString('?????!')"]);
  1. //Swift 
  2. let simplifyString: @objc_block String -> String = { input in 
  3.     var mutableString = NSMutableString(string: input) as CFMutableStringRef 
  4.     CFStringTransform(mutableString, nil, kCFStringTransformToLatin, Boolean(0)) 
  5.     CFStringTransform(mutableString, nil, kCFStringTransformStripCombiningMarks, Boolean(0)) 
  6.     return mutableString 
  7. context.setObject(unsafeBitCast(simplifyString, AnyObject.self), forKeyedSubscript: "simplifyString"
  8. println(context.evaluateScript("simplifyString('?????!')")) 
  9. // annyeonghasaeyo! 

需要注意的是,Swift的speedbump只适用于Objective-C block,对Swift闭包无用。要在一个JSContext里使用闭包,有两个步骤:一是用@objc_block来声明,二是将Swift的knuckle-whitening unsafeBitCast()函数转换为 AnyObject。

内存管理(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()。

  1. //Objective-C 
  2. // in Person.h ----------------- 
  3. @class Person; 
  4. @protocol PersonJSExports     @property (nonatomic, copy) NSString *firstName; 
  5.     @property (nonatomic, copy) NSString *lastName; 
  6.     @property NSInteger ageToday; 
  7.     - (NSString *)getFullName; 
  8.     // create and return a new Person instance with `firstName` and `lastName` 
  9.     + (instancetype)createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName; 
  10. @end 
  11. @interface Person : NSObject     @property (nonatomic, copy) NSString *firstName; 
  12.     @property (nonatomic, copy) NSString *lastName; 
  13.     @property NSInteger ageToday; 
  14. @end 
  15. // in Person.m ----------------- 
  16. @implementation Person 
  17. - (NSString *)getFullName { 
  18.     return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName]; 
  19. + (instancetype) createWithFirstName:(NSString *)firstName lastName:(NSString *)lastName { 
  20.     Person *person = [[Person alloc] init]; 
  21.     person.firstName = firstName; 
  22.     person.lastName = lastName; 
  23.     return person; 
  24. @end 
  1. //Swift 
  2. // Custom protocol must be declared with `@objc` 
  3. @objc protocol PersonJSExports : JSExport { 
  4.     var firstName: String { get set } 
  5.     var lastName: String { get set } 
  6.     var birthYear: NSNumber? { get set } 
  7.     func getFullName() -> String 
  8.     /// create and return a new Person instance with `firstName` and `lastName` 
  9.     class func createWithFirstName(firstName: String, lastName: String) -> Person 
  10. // Custom class must inherit from `NSObject` 
  11. @objc class Person : NSObject, PersonJSExports { 
  12.     // properties must be declared as `dynamic` 
  13.     dynamic var firstName: String 
  14.     dynamic var lastName: String 
  15.     dynamic var birthYear: NSNumber? 
  16.     init(firstName: String, lastName: String) { 
  17.         self.firstName = firstName 
  18.         self.lastName = lastName 
  19.     } 
  20.     class func createWithFirstName(firstName: String, lastName: String) -> Person { 
  21.         return Person(firstName: firstName, lastName: lastName) 
  22.     } 
  23.     func getFullName() -> String { 
  24.         return "\(firstName) \(lastName)" 
  25.     } 

配置JSContext

创建Person类之后,需要先将其导出到JavaScript环境中去,同时还需导入Mustache JS库,以便对Person对象应用模板。

  1. //Objective-C 
  2. // export Person class 
  3. context[@"Person"] = [Person class]; 
  4. // load Mustache.js 
  5. NSString *mustacheJSString = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil]; 
  6. [context evaluateScript:mustacheJSString];
  1. //Swift 
  2. // export Person class 
  3. context.setObject(Person.self, forKeyedSubscript: "Person"
  4. // load Mustache.js 
  5. if let mustacheJSString = String(contentsOfFile:..., encoding:NSUTF8StringEncoding, error:nil) { 
  6.     context.evaluateScript(mustacheJSString) 

JavaScript数据&处理

以下简单列出一个JSON范例,以及用JSON来创建新Person实例。

注意:JavaScriptCore实现了Objective-C/Swift的方法名和JavaScript代码交互。因为JavaScript没有命名好的参数,任何额外的参数名称都采取驼峰命名法(Camel-Case),并附加到函数名称上。在此示例中,Objective-C的方法createWithFirstName:lastName:在JavaScript中则变成了createWithFirstNameLastName()。

  1. //JSON 
  2.     { "first""Grace",     "last""Hopper",   "year"1906 }, 
  3.     { "first""Ada",       "last""Lovelace""year"1815 }, 
  4.     { "first""Margaret",  "last""Hamilton""year"1936 } 
  5. ]
  1. //JavaScript 
  2. var loadPeopleFromJSON = function(jsonString) { 
  3.     var data = JSON.parse(jsonString); 
  4.     var people = []; 
  5.     for (i = 0; i < data.length; i++) { 
  6.         var person = Person.createWithFirstNameLastName(data[i].first, data[i].last); 
  7.         person.birthYear = data[i].year; 
  8.         people.push(person); 
  9.     } 
  10.     return people; 

动手一试

现在你只需加载JSON数据,并在JSContext中调用,将其解析到Person对象数组中,再用Mustache模板渲染即可:

  1. //Objective-C 
  2. // get JSON string 
  3. NSString *peopleJSON = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil]; 
  4. // get load function 
  5. JSValue *load = context[@"loadPeopleFromJSON"]; 
  6. // call with JSON and convert to an NSArray 
  7. JSValue *loadResult = [load callWithArguments:@[peopleJSON]]; 
  8. NSArray *people = [loadResult toArray]; 
  9. // get rendering function and create template 
  10. JSValue *mustacheRender = context[@"Mustache"][@"render"]; 
  11. NSString *template = @"{{getFullName}}, born {{birthYear}}"
  12. // loop through people and render Person object as string 
  13. for (Person *person in people) { 
  14.    NSLog(@"%@", [mustacheRender callWithArguments:@[template, person]]); 
  15. // Output: 
  16. // Grace Hopper, born 1906 
  17. // Ada Lovelace, born 1815 
  18. // Margaret Hamilton, born 1936 
  1. //Swift 
  2. // get JSON string 
  3. if let peopleJSON = NSString(contentsOfFile:..., encoding: NSUTF8StringEncoding, error: nil) { 
  4.     // get load function 
  5.     let load = context.objectForKeyedSubscript("loadPeopleFromJSON"
  6.     // call with JSON and convert to an array of `Person` 
  7.     if let people = load.callWithArguments([peopleJSON]).toArray() as? [Person] { 
  8.         // get rendering function and create template 
  9.         let mustacheRender = context.objectForKeyedSubscript("Mustache").objectForKeyedSubscript("render"
  10.         let template = "{{getFullName}}, born {{birthYear}}" 
  11.         // loop through people and render Person object as string 
  12.         for person in people { 
  13.             println(mustacheRender.callWithArguments([template, person])) 
  14.         } 
  15.     } 
  16. // Output: 
  17. // Grace Hopper, born 1906 
  18. // Ada Lovelace, born 1815 
  19. // Margaret Hamilton, born 1936 
责任编辑:chenqingxiang 来源: codeceo
相关推荐

2023-05-16 15:32:45

JavaScriptWeb前端工程师

2014-08-01 15:16:05

SwiftC语言

2009-06-24 10:49:08

Unix

2010-10-08 09:42:23

JavaScript方

2019-04-23 15:20:26

JavaScript对象前端

2012-04-11 10:39:32

Eclipse

2020-06-18 10:26:43

JavaScript开发技术

2020-09-14 14:18:05

Vue和React

2022-11-04 09:01:33

SwiftPlottable

2015-07-06 10:02:57

Swift编译配置

2022-11-30 15:01:11

React技巧代码

2020-06-04 08:17:44

JavaScript延展操作运算符开发

2016-01-25 15:09:22

JavaScriptC程序

2023-10-04 07:25:59

JavaScriptpromises

2015-08-27 09:46:09

swiftAFNetworkin

2014-07-02 09:47:06

SwiftCocoaPods

2021-12-24 08:55:58

苹果 iOS 15 SwiftUI

2011-09-07 09:51:27

Javascript

2011-08-31 16:30:19

Lua多线程

2018-11-26 09:20:26

GrailsjQueryDataTables
点赞
收藏

51CTO技术栈公众号