How to send events from HTML running inside a UIWebView to native Objective-C code?

前端 未结 4 1608
暖寄归人
暖寄归人 2021-02-04 14:44

I want to integrate a full HTML framework (ie HTML/CSS/JavaScript) inside an iOS app and make the UIWebView in charge of running the HTML content being able to communicate with

4条回答
  •  眼角桃花
    2021-02-04 15:29

    I have done this using jQuery and UIWebViewDelegate:

    JavaScript (jQuery mobile):

    $("#bloodType").change(function() {
        url = $("#bloodType option:selected").text();
        url = "donordialog:bloodTypeChanged(" + url + ")";
        window.location = url;
    });
    

    So, the resulting URL looks like: donordialog:bloodTypeChanged(typeAB-)

    In my objc code:

    -(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        NSURL *URL = [request URL];
        if ([[URL scheme] isEqualToString:@"donordialog"])
        {
            // now we need to figure out the function part
            NSString *functionString = [URL resourceSpecifier];
    
            if ([functionString hasPrefix:@"bloodTypeChanged"])
            {
                // the blood type has changed, now do something about it.
                NSString *parameter = [functionString stringByReplacingOccurrencesOfString:@"bloodTypeChanged" withString:@""];
    
                // remove the '(' and then the ')'
                parameter = [parameter stringByReplacingOccurrencesOfString:@"(" withString:@""];
                parameter = [parameter stringByReplacingOccurrencesOfString:@")" withString:@""];
    
                // log the paramter, as I don't know what to do with it right now
                NSLog(@"%@", parameter);
            }
    
            return NO;
        }
    
        return YES;
    }
    

    This code was copied verbatim from a project I am currently working on, and can verify that this works.

提交回复
热议问题