2008-09-18 54 views

回答

12

这记录在developer.apple.com

+0

感谢,种种原因错过了,在我的谷歌搜索:) – georgebrock 2008-09-18 13:25:10

+2

对于任何搜索iOS的帮助,注意上面的答案是苹果只。 – zekel 2012-03-23 17:46:18

+1

请注意,链接已更改,因此此链接专用答案已无用。 – 2012-08-10 21:06:24

1

我有一个使用NimbleKit的解决方案。它可以从Javascript调用Objective C函数。

3

觉得挺绿,苹果的文档是我很不能使用,所以我做了呼吁在可可JavaScript和反之亦然Objective C的方法的概念证明,尽管后者容易得多。

首先确保你有你的WebView作为setFrameLoadDelegate:

[testWinWebView setFrameLoadDelegate:self]; 

你需要告诉的WebView尽快观看特定对象,因为它的加载:

- (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowScriptObject forFrame:(WebFrame *)frame { 
    //add the controller to the script environment 
    //the "ObjCConnector" object will now be available to JavaScript 
    [windowScriptObject setValue:self forKey:@"ObjCConnector"]; 
} 

那么企业的沟通:

// a few methods to log activity 
- (void)acceptJavaScriptFunctionOne:(NSString*) logText { 
    NSLog(@"acceptJavaScriptFunctionOne: %@",logText); 
} 
- (void)acceptJavaScriptFunctionTwo:(NSString*) logText { 
    NSLog(@"acceptJavaScriptFunctionTwo: %@",logText); 
} 

//this returns a nice name for the method in the JavaScript environment 
+(NSString*)webScriptNameForSelector:(SEL)sel { 
    NSLog(@"%@ received %@ with sel='%@'", self, NSStringFromSelector(_cmd), NSStringFromSelector(sel)); 
    if(sel == @selector(acceptJavaScriptFunctionOne:)) 
     return @"functionOne"; // this is what you're sending in from JS to map to above line 
    if(sel == @selector(acceptJavaScriptFunctionTwo:)) 
     return @"functionTwo"; // this is what you're sending in from JS to map to above line 
    return nil; 
} 

//this allows JavaScript to call the -logJavaScriptString: method 
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)sel { 
    NSLog(@"isSelectorExcludedFromWebScript: %@", NSStringFromSelector(sel)); 
    if(sel == @selector(acceptJavaScriptFunctionOne:) || 
     sel == @selector(acceptJavaScriptFunctionTwo:)) 
     return NO; 
    return YES; 
} 

关键是,如果你有多种方法你想调用,你需要在isSelectorExcludedFromWebScript方法中全部排除它们,并且你需要javascript调用映射到webScriptNameForSelector中的ObjC方法。概念文件的

全部项目证明: https://github.com/bytestudios/JS-function-and-ObjC-method-connector

相关问题