UIWebview中的NSString
问题描述:
我在我的项目中有一个NSString
和一个webView(Objective-C for iPhone),我在webView中调用了index.html
,并且在其中插入了我的脚本(javascript)。UIWebview中的NSString
如何将NSString作为var传递给我的脚本,反之亦然?
这是一个example,但我不太了解它。
答
发送字符串Web视图:
[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"];
发送字符串从网页视图对象 - 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';
+3
和其他方式呢? :-) – MJB 2012-05-05 18:34:12
答
当通过一个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];
r反向过程很好地描述@迈克尔凯斯勒
我已经添加了UIWebView和UIWebViewDelegate标签(而不是xcode和html) – 2010-09-18 17:13:53