Call Objective C method from JavaScript with parameter
I succee开发者_运维知识库d to call a Objective C method from a JavaScript method using the following
///javascript
function hi()
{
CallNKitAction("callFromJavascript className=TestCarouselViewController&index="+index);
}
hi();
////objective c
-(void)callFromJavascript
{
NSLog(@"Before:%f",refToSelf.carouselView.alpha);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.6f];
refToSelf.carouselView.alpha=0.0f;
[UIView commitAnimations];
NSLog(@"After:%f",refToSelf.carouselView.alpha);
}
but I don't know how to call with a parameter. Can anyone help?
Here is some code sample (inside the Objective-C):
- (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:"index"]) {
// Use the index...
}
}
}
}
return NO;
}
else {
return YES;
}
}
Inside JS:
location.href = 'myApp://index=10';
Noticing that this is unanswered - I have a little project that simplifies the calling of Objective-C from UIWebViews.
It provides a small Javascript function to invoke the Objective-C and a class (called KPWebViewInterceptor) that sits between your WebView and ViewController.
You can read about it and download from: https://github.com/dannywartnaby/KPWebViewInterceptor
You'll have to do that with the UIWebViewDelegate. You probably already have a UIWebView, the only thing you have to do is to check out this delegate-method:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
Source: http://developer.apple.com/iphone/library/documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html
精彩评论