UIWebview中的NSString [英] NSString in UIWebview
问题描述
我的项目中有一个 NSString
和一个webView(iPhone的Objective-C),我打电话给 index.html
在webView中,我插入了我的脚本(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"];
从网络视图发送字符串到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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!