Search code examples
iosobjective-cuiwebview

Passing a value from Objective-C to JS file


Looking for a way to pass the NSArray to JS file.

As I was doing this previously making whole JS as NSString.Like the following:

NSString *html = [NSString stringWithFormat:@"<div id='check'></div><script> var j, currentOption='', jsArray = new Array %@, selectedArray1 = new Array %@, str=''; for(j = 0; j< %lu;  j++){ checked=''; for(k=0; k<selectedArray1.length; k++){ if(\"'\"+j+\"'\"==selectedArray1[k]){checked='checked';currentOption
+= j+',';} } str += '<label><input type=\"checkbox\" id=\"one_'+j+'\" '+checked+' name = \"Dee[]\" value = \"'+jsArray[j]+'\" style=\"width:20px;height:60px;vertical-align: middle;position: relative;bottom: 1px;\"  onclick=\"showvalue(this.value);\" />'+jsArray[j]+'</label><br/><br/>'; } document.getElementById(\"check\").innerHTML=str; function showvalue(){currentOption='';for(j = 0; j< %lu;  j++){ if(document.getElementById('one_'+j).checked){currentOption += j+'^';} }} </script>",newArray,oldArray,(unsigned long)newArray.count,(unsigned long)newArray.count];

and then loading this String in webview using the following:

 [self.webView loadHTMLString:[NSString stringWithFormat:@"%@ \n\r <br/><br/> %@",[self.Array objectAtIndex:self.postion][@"question"],html] baseURL:nil];

Now i have the separate JS file and i am loading the JS file as :

NSString *filePathForJS = [[NSBundle mainBundle] pathForResource:@"JSFile" ofType:@"js"];
NSURL* jsFile  = [NSURL fileURLWithPath:filePathForJS];
[self.webView loadHTMLString:[NSString stringWithFormat:@"<div id='check'></div><br/><br/><script src=\"%@\" type='text/javascript'></script><script>document.getElementById(\"check\").innerHTML='%@';</script>",jsFile,[self.questionArray objectAtIndex:self.postion][@"question"]] baseURL:nil];

I wanna pass array to the JS array declared in file. How can i achieve this?


Solution

  • Loaded the Array from objective c code as string

    NSString *filePathForCross = [[NSBundle mainBundle] pathForResource:@"Q-11" ofType:@"js"];
    NSURL* jsFile  = [NSURL fileURLWithPath:filePathForCross];
    NSString* content = [NSString stringWithContentsOfFile:filePathForCross
                                                  encoding:NSUTF8StringEncoding
                                                     error:NULL];
    NSString *tmpstring=[NSString stringWithFormat:@"%@",[self.questionArray objectAtIndex:self.indexCount]
    NSString *ttmpstring=[NSString stringWithFormat:@"<div id='check'></div><script> var optionArray = %@; %@ %@</script>",tmpstring,content,jsFunTohighlightDiv];
    
    NSLog(@"Here options array: %@",ttmpstring);
    [self.webView loadHTMLString:[NSString stringWithFormat:@"%@ \n\r <br/><br/> %@",[self.questionArray objectAtIndex:self.indexCount][QuestionLang],ttmpstring] baseURL:nil];