PowenKo > iOS > UIWebView > Javascript call iOS


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    mUIWebView=[[UIWebView alloc] initWithFrame:self.view.frame];
    
    
    [mUIWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

    mUIWebView.delegate=self;
    [self.view addSubview:mUIWebView];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = [[request URL] absoluteString];
    
    NSArray *urlArray = [url componentsSeparatedByString:@"?"];
    NSString *cmd = @"";
    NSMutableArray *paramsToPass = nil;
    if([urlArray count] > 1){
        NSString *FunctionName = [urlArray objectAtIndex:0];
        
         NSArray *urlArray2 = [FunctionName componentsSeparatedByString:@"/"];
        int t_urlArray2Count=[urlArray2 count];
        FunctionName = [urlArray2 objectAtIndex:t_urlArray2Count-1];
        
         NSLog(FunctionName);
            if ([FunctionName isEqualToString:@"callback"])
            {
                NSString *paramsString = [urlArray objectAtIndex:1];
                NSArray *urlParamsArray = [paramsString componentsSeparatedByString:@"&"];
                cmd = [[[urlParamsArray objectAtIndex:0] componentsSeparatedByString:@"="] objectAtIndex:1];
                int numCommands = [urlParamsArray count];
                paramsToPass = [[NSMutableArray alloc] initWithCapacity:numCommands-1];
                for(int i = 1; i < numCommands; i++){
                    NSString *aParam = [[[urlParamsArray objectAtIndex:i] componentsSeparatedByString:@"="] objectAtIndex:1];
                    [paramsToPass addObject:aParam];
                    NSLog(aParam);
                }
                [mUIWebView stringByEvaluatingJavaScriptFromString:@"sayHello()"];
                
            }
        return NO;
    }
    return YES;
    
}


index.html

<html>
    <body>
        <input type="button" value="callback" onclick='window.location="callback?cmd=getLocation&param=aParam"' />
    </body>
</html>

Leave a Reply