NSString in UIWebview

倾然丶 夕夏残阳落幕 提交于 2019-11-26 09:29:11

问题


I have an NSString and a webView in my project (Objective-C for iPhone), I have called index.html in webView and inside it I inserted my script (javascript).

How can I pass the NSString as a var in my script and viceversa?

This is an example, but I don\'t understand it very well.


回答1:


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 .m 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';



回答2:


When passing an NSString into a UIWebView (for use as a javascript String) you need to make sure to escape newlines as well as single/double quotes:

NSString *html = @"<div id='my-div'>Hello there</div>";

html = [html stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
html = [html stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
html = [html stringByReplacingOccurrencesOfString:@"\r" withString:@""];

NSString *javaScript = [NSString stringWithFormat:@"injectSomeHtml('%@');", html];
[_webView stringByEvaluatingJavaScriptFromString:javaScript];

The reverse process is well described by @Michael-Kessler



来源:https://stackoverflow.com/questions/3742590/nsstring-in-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!