2008-09-18 8 views

Antwort

12

Dies ist dokumentiert unter developer.apple.com.

+0

Danke, irgendwie verpasst, dass in meinem Google sucht :) – georgebrock

+2

Für jedermann für iOS Hilfe suchen, beachten Sie, dass die oben genannte Antwort ist Mac-only. – zekel

+1

Beachten Sie, dass sich der Link geändert hat, sodass diese Nur-Link-Antwort nicht mehr nützlich ist. –

1

Ich habe eine Lösung mit NimbleKit. Es kann Objective C-Funktionen von Javascript aufrufen.

+4

wie sehr nett für Sie, wie wäre es, es zu teilen? – Jonathan

3

Da Apple ziemlich grün ist, ist die Dokumentation für mich ziemlich unbrauchbar, deshalb habe ich in Cocoa einen Konzeptnachweis für das Aufrufen von Objective-C-Methoden aus JavaScript und umgekehrt erstellt, obwohl Letzteres viel einfacher war.

Zuerst sollten Sie sich Ihre webview als setFrameLoadDelegate haben:

[testWinWebView setFrameLoadDelegate:self]; 

Sie müssen die Webansicht sagen, für ein bestimmtes Objekt so schnell zu sehen, wie es geladen wird:

- (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"]; 
} 

Dann das Geschäft der Kommunikation:

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

Der Schlüssel ist, dass, wenn Sie mehrere Methoden haben Sie möchten sie aufrufen, Sie müssen sie alle in der Methode isSelectorExcludedFromWebScript ausschließen, und Sie benötigen den JavaScript-Aufruf, um die ObjC-Methode in webScriptNameForSelector abzubilden.

Voll Projekt Konzeptnachweis-Datei: https://github.com/bytestudios/JS-function-and-ObjC-method-connector

+0

Danke für nützliche Informationen. Diese Antwort hilft mir wirklich sehr !! – Tommy