1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Objective-C methods from Javascript in Cocoa

Discussion in 'Mac Programming' started by aruns1, Mar 26, 2012.

  1. macrumors newbie

    #1
    Hello!
    I have a webview control in a Cocoa application where I am showing a web page. I need to access Objective-C method from Javascript in HTML page shown in Webview. I have tried "Calling Objective-C Methods From JavaScript"
    from apple site "https://developer.apple.com/library/mac/#documentation/appleapplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html". But it did not worked. Pleases help me to Call Objective-C methods from Javascript.
     
  2. macrumors 68040

    lee1210

    #2
    The document from your post looks like it should get you where you're wanting to go. Post your code and tell us what happens. Is your exposed object undefined in javascript? Is it defined, but the methods you expect are not? Are the methods defined but there is some failure when you try to call them?

    Post your code and a more complete description of its behavior and we'll be glad to help.

    -Lee
     
  3. aruns1, Mar 27, 2012
    Last edited by a moderator: Mar 27, 2012

    macrumors newbie

    #3
    I have a class ObjCMethods as below
    Code:
    #import "ObjCMethods.h"
    
    @implementation ObjCMethods
    
    - (int)studentsInClass:(int)standard;
    {
    	return 20;
    }
    @end
    with just one method as above. 
    
    Also I am displaying an html page in webview as below:-
    
    #import "Controller.h"
    #import "ObjCMethods.h"
    #import <WebKit/WebKit.h>
    
    @implementation Controller
    -(void)awakeFromNib
    {
    	
    	
    	[[_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"/Users/abcd/Desktop/sample.html"]]];
    	ObjCMethods *record1 = [[ObjCMethods alloc] init];
    	
    	
    	
    	id win = [_webView windowScriptObject];
    	
    	[win setValue:record1 forKey:@"ObjCMethods"];
    }
    
    @end
    
    _webview is outlet to Webview in the xib file.

    The code for html page is as below:-
    Code:
    <html>
    <body>
    <script type="text/javascript">
    var i=0;
    while (i<=5)
      {
      document.write("The number is " + i);
      document.write("<br />");
      i++;
      }
    var myrecord = window.ObjCMethods;
    var studentsCount = studentsInClass_(5);
    document.write(studentsCount);
    </script>
    </body>
    </html>
    
    I expect output to be
    The number is 0
    The number is 1
    The number is 2
    The number is 3
    The number is 4
    The number is 5
    20
    But at bootom 20 is missing from the original output showing that Objective-C method is not being called.
     
  4. macrumors 68040

    lee1210

    #4
    Try calling studentsInClass_ on myrecord in your JavaScript, rather than treating it as a global method.

    -Lee
     

Share This Page