Reputation: 615
I have an array which has some data of lines where I have to display it in onclick of a button in javascript, so how to call a array which is coded in objective C in javascript or to html file. The following is my Objective c code:
- (void)viewDidLoad
{
[super viewDidLoad];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"Array"ofType:@"html"]isDirectory:NO]]];
NSString *path = [[NSBundle mainBundle] pathForResource:@"Example" ofType:@"csv"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\n,"]];
for (NSString* line in lines) {
NSLog(@"%@", line);
}
NSLog(@" %d", [lines count]);
}
Upvotes: 0
Views: 690
Reputation: 174
JSON-encode the NSStrings or NSArray (lines
) you want to use in JavaScript. json-framework is a popular JSON library for Obj-C. You will end up with an NSString
that represents your data.
Use stringByEvaluatingJavaScriptFromString:
and use your JSON string there as a parameter to a function call or however else you see fit.
Example:
NSString *jsonLines = [lines JSONRepresentation];
NSString *javascript = [NSString stringWithFormat:@"myJavascriptFunctionThatProcessesLines(%@);", jsonLines];
[webView stringByEvaluatingJavaScriptFromString:javascript];
Sample JavaScript function:
function myJavascriptFunctionThatProcessesLines(lines) {
for(var line in lines) {
alert(line); // Or whatever
}
}
Upvotes: 0
Reputation: 1785
Check out this library:
http://code.google.com/p/jsbridge-to-cocoa/
Upvotes: 1