Created
May 21, 2018 12:54
-
-
Save abner/87c8544a1840c59ca55101afe0d86960 to your computer and use it in GitHub Desktop.
Objective-C execute Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.m | |
// app-with-jscontext | |
// | |
// Created by DE505 on 21/05/2018. | |
// Copyright © 2018 DE505. All rights reserved. | |
// | |
#import "ViewController.h" | |
@import JavaScriptCore; | |
@interface ViewController () | |
@end | |
@implementation ViewController | |
- (void)viewDidLoad { | |
[super viewDidLoad]; | |
// Do any additional setup after loading the view, typically from a nib. | |
// getting a JSContext | |
JSContext *context = [JSContext new]; | |
context[@"consoleLog"] = ^(NSString *message) { | |
NSLog(@"Javascript Log: %@", message); | |
}; | |
// enable exception handling | |
[context setExceptionHandler:^(JSContext *context, JSValue *value) { | |
NSLog(@"%@", value); | |
}]; | |
NSString *myScript = @"var result = 0;" | |
" consoleLog('Hello world');" | |
" function a() { return Promise.resolve(39); }" | |
" function b() { return Promise.resolve(1); }" | |
" a().then((r) => consoleLog(r.toString()));"; | |
[context evaluateScript:myScript]; | |
JSValue *result = context[@"result"]; | |
NSLog(@"%@", result); | |
NSString *phone = @"71 878782782"; | |
// defining a JavaScript function | |
NSString *jsFunctionText = | |
@"var isValidNumber = function(phone) {" | |
" var phonePattern = /^[0-9]{3}[ ][0-9]{3}[-][0-9]{4}$/;" | |
" return phone.match(phonePattern) ? true : false;" | |
"}"; | |
[context evaluateScript:jsFunctionText]; | |
// calling a JavaScript function | |
JSValue *jsFunction = context[@"isValidNumber"]; | |
JSValue *value = [jsFunction callWithArguments:@[ phone ]]; | |
NSLog(@"%@", value); | |
} | |
- (void)didReceiveMemoryWarning { | |
[super didReceiveMemoryWarning]; | |
// Dispose of any resources that can be recreated. | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment