简体   繁体   中英

Objective-c [For loop] load HTML in UIWebview and retrieve data from JavaScript function

I'm making an app in Objective-c for IOS and I need to be able to loop through a bunch of web pages and, using an embedded javascript function return some JSON values.

I use the pages elsewhere in the app and the javascript works as required. At this point I do store the JSON response but as user might not view every page the app wont necessarily have all the JSON values to check.

The section of code below is what I'm using to loop through all the pages, load in the HTML string and run the javascript function. The problem is that the values always come back empty.

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finished loading");
    NSString *jsonValues = [webView stringByEvaluatingJavaScriptFromString:@"getFields()"];
}

for (int i = 1; i <= shifts; i++)
    {
        ontracMultipleWevViewController *RT9909 = [viewControllerDictionary objectForKey:[NSString stringWithFormat:@"Shift %d RT9909", i]];
        if (RT9909 && [RT9909.viewControllers count] > 0) {
            for (ontracRTViewController *r9909 in RT9909.viewControllers) {

                 UIWebView *webView = [[UIWebView alloc] init];
                 [webView setDelegate: self];
                 [webView loadHTMLString:r9909.htmlString baseURL:[NSURL URLWithString:r9909.urlToLoad]];
                [self webViewDidFinishLoad:webView];
                [self.view addSubview:webView];

                if([self webViewDidFinishLoad:webView]){
                    r9909.jsonValues = [webView stringByEvaluatingJavaScriptFromString:@"getFields()"];

                   if(r9909.jsonValues != nil && ![r9909.jsonValues isEqualToString:@""] && rt9909ShiftCount == 0){

                   ........rest of code

NOTE: I get no error or NSLogs to suggest any problems

You need to segregate the

if([self webViewDidFinishLoad:webView]){
    r9909.jsonValues = [webView stringByEvaluatingJavaScriptFromString:@"getFields()"];

block out of the for-loop & add tags to your webviews.


Implement the

- (void)webViewDidFinishLoad:(UIWebView *)webView;

optional delegate function of UIWebView & put in your


if(...) {
      r9909.jsonValues = [webView stringByEvaluatingJavaScriptFromString:@"getFields()"];
 }


logic here.
The if check would now be based on the webview.tag that you will assign will creating the webviews inside the for loop .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM