使用参数从JavaScript调用Objective C方法

时间:2010-07-18 10:10:29

标签: javascript iphone objective-c

我成功使用以下

从JavaScript方法调用Objective C方法
///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);

}

但我不知道如何使用参数调用。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

以下是一些代码示例(在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;
    }
}

JS内部:

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

答案 1 :(得分:2)

注意到这是没有答案的 - 我有一个小项目,简化了从UIWebViews调用Objective-C。

它提供了一个小的Javascript函数来调用Objective-C和一个位于WebView和ViewController之间的类(称为KPWebViewInterceptor)。

您可以阅读并下载:https://github.com/dannywartnaby/KPWebViewInterceptor

答案 2 :(得分:0)

您必须使用UIWebViewDelegate执行此操作。你可能已经有了一个UIWebView,你唯一要做的就是检查这个委托方法:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

来源: http://developer.apple.com/iphone/library/documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html