简体   繁体   中英

Injecting JQuery function in Objective-c in UIWebView

I have this function in jquery saved as doc2.js in my Target and i had copy in my bundle resources as follow:

doc2.js:

  $(document).ready(function(){
  $(".flip").click(function(){
  $(".panel").slideToggle("slow");
     });
       });

at my Xcode i have the following:

 UIWebView * webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
 [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"new" ofType:@"html"]isDirectory:NO]]];
 webView.delegate=self;
 [self.view addSubview:webView];

and this method :

-(void)webViewDidFinishLoad:(UIWebView *)webView {
 NSString *jqueryCDN = @"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
 NSData *jquery = [NSData dataWithContentsOfURL:[NSURL URLWithString:jqueryCDN]];
 NSString *jqueryString = [[NSMutableString alloc] initWithData:jquery encoding:NSUTF8StringEncoding];
 [webView stringByEvaluatingJavaScriptFromString:jqueryString];
 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"doc2" ofType:@"js" inDirectory:NO];
 NSData *fileData = [NSData dataWithContentsOfFile:filePath];
 NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
 [webView stringByEvaluatingJavaScriptFromString:jsString];}

In my html file:

<!DOCTYPE html>
 <html>
    <head>        
         <script type="text/javascript" src="jquery.js"></script>
         <style type="text/css"> 
             div.panel,p.flip
            {
                 margin:0px;
                 padding:5px;
                 text-align:center;
                 background:#e5eecc;
                 border:solid 1px #c3c3c3;
             }
             div.panel
             {
                 height:120px;
                 display:none;
             }
             </style>
     </head>
     <body>    
         <div class="panel">
            <p>Any Thing.</p>
            <p>Any Thing.</p>
         </div>        
         <p class="flip">Show/Hide Panel</p>
            </body>
 </html>

this code should handle the UIWebView but its not working with me I think that my jQuery function is not completed or something like that Any idea ??

You may want to try a different approach: Either include a local copy or download jquery from a cdn. Doing both seems unnecessary.

Moreover: Just define a javascript function in your doc2.js, include the file in the HTML and call it directly within Cocoa. Make sure you exposed your functions to Cocoa with

isSelectorExcludedFromWebScript

Calling is possible with

evaluateWebScript

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