歡迎加入QQ討論群258996829
來自星星的你 頭像
蘋果3袋
3
來自星星的你

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

發(fā)布時(shí)間:2015-01-27 19:40  回復(fù):0  查看:2795   最后回復(fù):2015-01-27 19:40  

本文作者Nate Cook是一位獨(dú)立的Web及移動(dòng)應(yīng)用開發(fā)者,是繼Mattt大神之后NSHipster的主要維護(hù)者,也是非常知名活躍的Swift博主,并且還是支持自動(dòng)生成Swift在線文檔的SwiftDoc.org網(wǎng)站創(chuàng)造者。在本文中,他介紹了在Swift中使用JavaScript的方法和技巧,對(duì)于iOS和Web應(yīng)用工程師有著非常實(shí)用的價(jià)值,以下為譯文:

在RedMonk發(fā)布的2015年1月編程語言排行榜中,Swift采納率排名迅速飆升,從剛剛面世時(shí)的68位躍至22位,Objective-C仍然穩(wěn)居TOP10,而JavaScript則憑借著其在iOS平臺(tái)上原生體驗(yàn)優(yōu)勢(shì)成為了年度最火熱的編程語言。

647cc7d1b5d97a2d854759ccb3e994e7.jpg

而早在2013年蘋果發(fā)布的OS X Mavericks和iOS 7兩大系統(tǒng)中便均已加入了JavaScriptCore框架,能夠讓開發(fā)者輕松、快捷、安全地使用JavaScript語言編寫應(yīng)用。不論叫好叫罵,JavaScript霸主地位已成事實(shí)。開發(fā)者們趨之若鶩,JS工具資源層出不窮,用于OS

X和iOS系統(tǒng)等高速虛擬機(jī)也蓬勃發(fā)展起來。

JSContext/JSValue

JSContext即JavaScript代碼的運(yùn)行環(huán)境。一個(gè)Context就是一個(gè)JavaScript代碼執(zhí)行的環(huán)境,也叫作用域。當(dāng)在瀏覽器中運(yùn)行JavaScript代碼時(shí),JSContext就相當(dāng)于一個(gè)窗口,能輕松執(zhí)行創(chuàng)建變量、運(yùn)算乃至定義函數(shù)等的JavaScript代碼:

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

//Swift
let 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)")

像JavaScript這類動(dòng)態(tài)語言需要一個(gè)動(dòng)態(tài)類型(Dynamic Type), 所以正如代碼最后一行所示,JSContext里不同的值均封裝在JSValue對(duì)象中,包括字符串、數(shù)值、數(shù)組、函數(shù)等,甚至還有Error以及null和undefined。

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

Unnamed QQ Screenshot20150127134722.png

想要檢索上述示例中的tripleNum值,只需使用相應(yīng)的方法即可:

//Objective-C
NSLog(@"Tripled: %d", [tripleNum toInt32]);
// Tripled: 30

//Swift
println("Tripled: \(tripleNum.toInt32())")
// Tripled: 30

下標(biāo)值(Subscripting Values)

通過在JSContext和JSValue實(shí)例中使用下標(biāo)符號(hào)可以輕松獲取上下文環(huán)境中已存在的值。其中,JSContext放入對(duì)象和數(shù)組的只能是字符串下標(biāo),而JSValue則可以是字符串或整數(shù)下標(biāo)。

//Objective-C
JSValue *names = context[@"names"];
JSValue *initialName = names[0];
NSLog(@"The first name: %@", [initialName toString]);
// The first name: Grace

//Swift
let names = context.objectForKeyedSubscript("names")
let initialName = names.objectAtIndexedSubscript(0)
println("The first name: \(initialName.toString())")
// The first name: Grace

而Swift語言畢竟才誕生不久,所以并不能像Objective-C那樣自如地運(yùn)用下標(biāo)符號(hào),目前,Swift的方法僅能實(shí)現(xiàn)objectAtKeyedSubscript()和objectAtIndexedSubscript()等下標(biāo)。

函數(shù)調(diào)用(Calling Functions)

我們可以將Foundation類作為參數(shù),從Objective-C/Swift代碼上直接調(diào)用封裝在JSValue的JavaScript函數(shù)。這里,JavaScriptCore再次發(fā)揮了銜接作用。

//Objective-C
JSValue *tripleFunction = context[@"triple"];
JSValue *result = [tripleFunction callWithArguments:@[@5] ];
NSLog(@"Five tripled: %d", [result toInt32]);

//Swift
let tripleFunction = context.objectForKeyedSubscript("triple")
let result = tripleFunction.callWithArguments([5])
println("Five tripled: \(result.toInt32())")

異常處理(Exception Handling)

JSContext還有一個(gè)獨(dú)門絕技,就是通過設(shè)定上下文環(huán)境中exceptionHandler的屬性,可以檢查和記錄語法、類型以及出現(xiàn)的運(yùn)行時(shí)錯(cuò)誤。exceptionHandler是一個(gè)回調(diào)處理程序,主要接收J(rèn)SContext的reference,進(jìn)行異常情況處理。

//Objective-C
context.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


//Swift
context.exceptionHandler = { context, exception in
    println("JS Error: \(exception)")
}
context.evaluateScript("function multiply(value1, value2) { return value1 * value2 ")
// JS Error: SyntaxError: Unexpected end of script

JavaScript函數(shù)調(diào)用

了解了從JavaScript環(huán)境中獲取不同值以及調(diào)用函數(shù)的方法,那么反過來,如何在JavaScript環(huán)境中獲取Objective-C或者Swift定義的自定義對(duì)象和方法呢?要從JSContext中獲取本地客戶端代碼,主要有兩種途徑,分別為Blocks和JSExport協(xié)議。

Blocks (塊)

在JSContext中,如果Objective-C代碼塊賦值為一個(gè)標(biāo)識(shí)符,JavaScriptCore就會(huì)自動(dòng)將其封裝在JavaScript函數(shù)中,因而在JavaScript上使用Foundation和Cocoa類就更方便些——這再次驗(yàn)證了JavaScriptCore強(qiáng)大的銜接作用?,F(xiàn)在CFStringTransform也能在JavaScript上使用了,如下所示:

//Objective-C
context[@"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('?????!')"]);


//Swift
let 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!

需要注意的是,Swift的speedbump只適用于Objective-C block,對(duì)Swift閉包無用。要在一個(gè)JSContext里使用閉包,有兩個(gè)步驟:一是用@objc_block來聲明,二是將Swift的knuckle-whitening unsafeBitCast()函數(shù)轉(zhuǎn)換為 AnyObject。

內(nèi)存管理(Memory Management)

代碼塊可以捕獲變量引用,而JSContext所有變量的強(qiáng)引用都保留在JSContext中,所以要注意避免循環(huán)強(qiáng)引用問題。另外,也不要在代碼塊中捕獲JSContext或任何JSValues,建議使用[JSContext currentContext]來獲取當(dāng)前的Context對(duì)象,根據(jù)具體需求將值當(dāng)做參數(shù)傳入block中。

JSExport協(xié)議

借助JSExport協(xié)議也可以在JavaScript上使用自定義對(duì)象。在JSExport協(xié)議中聲明的實(shí)例方法、類方法,不論屬性,都能自動(dòng)與JavaScrip交互。文章稍后將介紹具體的實(shí)踐過程。

JavaScriptCore實(shí)踐

我們可以通過一些例子更好地了解上述技巧的使用方法。先定義一個(gè)遵循JSExport子協(xié)議PersonJSExport的Person model,再用JavaScript在JSON中創(chuàng)建和填入實(shí)例。有整個(gè)JVM,還要NSJSONSerialization干什么?

PersonJSExports和Person

Person類執(zhí)行的PersonJSExports協(xié)議具體規(guī)定了可用的JavaScript屬性。,在創(chuàng)建時(shí),類方法必不可少,因?yàn)镴avaScriptCore并不適用于初始化轉(zhuǎn)換,我們不能像對(duì)待原生的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

創(chuàng)建Person類之后,需要先將其導(dǎo)出到JavaScript環(huán)境中去,同時(shí)還需導(dǎo)入Mustache JS庫(kù),以便對(duì)Person對(duì)象應(yīng)用模板。

//Objective-C
// export Person class
context[@"Person"] = [Person class];
// load Mustache.js
NSString *mustacheJSString = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
[context evaluateScript:mustacheJSString];


//Swift
// export Person class
context.setObject(Person.self, forKeyedSubscript: "Person")
// load Mustache.js
if let mustacheJSString = String(contentsOfFile:..., encoding:NSUTF8StringEncoding, error:nil) {
    context.evaluateScript(mustacheJSString)
}

JavaScript數(shù)據(jù)&處理

以下簡(jiǎn)單列出一個(gè)JSON范例,以及用JSON來創(chuàng)建新Person實(shí)例。

注意:JavaScriptCore實(shí)現(xiàn)了Objective-C/Swift的方法名和JavaScript代碼交互。因?yàn)镴avaScript沒有命名好的參數(shù),任何額外的參數(shù)名稱都采取駝峰命名法(Camel-Case),并附加到函數(shù)名稱上。在此示例中,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 }
]


//JavaScript
var 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;
}

動(dòng)手一試

現(xiàn)在你只需加載JSON數(shù)據(jù),并在JSContext中調(diào)用,將其解析到Person對(duì)象數(shù)組中,再用Mustache模板渲染即可:

//Objective-C
// get JSON string
NSString *peopleJSON = [NSString stringWithContentsOfFile:... encoding:NSUTF8StringEncoding error:nil];
// get load function
JSValue *load = context[@"loadPeopleFromJSON"];
// call with JSON and convert to an NSArray
JSValue *loadResult = [load callWithArguments:@[peopleJSON]];
NSArray *people = [loadResult toArray];
// get rendering function and create template
JSValue *mustacheRender = context[@"Mustache"][@"render"];
NSString *template = @"{{getFullName}}, born {{birthYear}}";
// loop through people and render Person object as string
for (Person *person in people) {
   NSLog(@"%@", [mustacheRender callWithArguments:@[template, person]]);
}
// Output:
// Grace Hopper, born 1906
// Ada Lovelace, born 1815
// Margaret Hamilton, born 1936
//Swift
// get JSON string
if 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 1936

您還未登錄,請(qǐng)先登錄

熱門帖子

最新帖子

?