UIWebview 中的 NSString

NSString in UIWebview(UIWebview 中的 NSString)

本文介绍了UIWebview 中的 NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

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

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.

推荐答案

发送字符串到网页视图:

Send string to web view:

[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"];

<小时>

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


Send string from web view to Obj-C:

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

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

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

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

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

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

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

JS 内部:

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

这篇关于UIWebview 中的 NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:UIWebview 中的 NSString

基础教程推荐