views:

104

answers:

1

Hi, i have an NSString and a webView in my project (Objective-C for iPhone), i have called index.html in webView and in index.html i have written my script (javascript) How can i pass the NSString as a var in my script and viceversa? http://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html This is an example, but i don't understand very good this example. Excuse for my crappy english. Paki

+1  A: 

Send string to web view:

[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"];

Send string from web view to Obj-C:

Declare that you implement the UIWebViewDelegate protocol (inside the .h file):

@interface MyViewController : UIViewController <UIWebViewDelegate> {

    // your class members

}

// declarations of your properties and methods

@end

In Objective-C (inside the .m file):

// right after creating the web view
webView.delegate = self;

In Objective-C (inside the .h file) too:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *url = [[request URL] absoluteString];

    static NSString *urlPrefix = @"myApp://";

    if ([url hasPrefix:urlPrefix]) {
        NSString *paramsString = [url substringFromIndex:[urlPrefix length]];
        NSArray *paramsArray = [paramsString componentsSeparatedByString:@"&"];
        int paramsAmount = [paramsArray count];

        for (int i = 0; i < paramsAmount; i++) {
            NSArray *keyValuePair = [[paramsArray objectAtIndex:i] componentsSeparatedByString:@"="];
            NSString *key = [keyValuePair objectAtIndex:0];
            NSString *value = nil;
            if ([keyValuePair count] > 1) {
                value = [keyValuePair objectAtIndex:1];
            }

            if (key && [key length] > 0) {
                if (value && [value length] > 0) {
                    if ([key isEqualToString:"param"]) {
                        // Use the index...
                    }
                }
            }
        }

        return NO;
    }
    else {
        return YES;
    }
}

Inside JS:

location.href = 'myApp://param=10';
Michael Kessler