【问题标题】:NSString in UIWebviewUIWebview 中的 NSString
【发布时间】:2011-04-14 03:26:57
【问题描述】:

我的项目中有一个NSString 和一个webView(iPhone 的Objective-C),我在webView 中调用了index.html,并在其中插入了我的脚本(javascript)。

如何在脚本中将 NSString 作为 var 传递,反之亦然?

这是example,不过我不是很懂。

【问题讨论】:

  • 我已将 UIWebView 和 UIWebViewDelegate 添加到标签中(而不是 xcode 和 html)

标签: javascript iphone objective-c uiwebview uiwebviewdelegate


【解决方案1】:

发送字符串到网页视图:

[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"];

从 web 视图发送字符串到 Obj-C:

声明你实现了 UIWebViewDelegate 协议(在 .h 文件中):

@interface MyViewController : UIViewController <UIWebViewDelegate> {

    // your class members

}

// declarations of your properties and methods

@end

在 Objective-C 中(在 .m 文件中):

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

也在 Objective-C 中(在 .m 文件中):

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

JS 内部:

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

【讨论】:

  • 反之亦然? :-)
【解决方案2】:

将 NSString 传递给 UIWebView(用作 javascript 字符串)时,您需要确保转义换行符以及单/双引号:

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];

@Michael-Kessler 很好地描述了反向过程

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2013-06-18
    相关资源
    最近更新 更多