ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)

此解决方案原理:

1、在ViewController.h中声明方法和成员变量,以及webView的委托:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
//  ViewController.h
//  JS_IOS_01
//
//  Created by IMAC on 14-2-24.
//  Copyright (c) 2014年 Wanggsx. All rights reserved.
//
 
# import <uikit uikit.h= "" >
 
@interface ViewController : UIViewController<uiwebviewdelegate>
{}
@property (nonatomic,retain) IBOutlet UIWebView *webView;
// 两个参数
-( void )getParam1:(NSString*)str1 withParam2:(NSString*)str2;
@end </uiwebviewdelegate></uikit>

 

2、在ViewController.m中合成成员变量并实现该方法:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//
//  ViewController.m
//  JS_IOS_01
//
//  Created by IMAC on 14-2-24.
//  Copyright (c) 2014年 Wanggsx. All rights reserved.
//
 
# import ViewController.h
 
@interface ViewController ()
 
@end
 
@implementation ViewController
@synthesize webView;
- ( void )viewDidLoad
{
     [ super viewDidLoad];
}
 
- ( void )didReceiveMemoryWarning
{
     [ super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
}
 
-( void )getParam1:(NSString*)str1 withParam2:(NSString*)str2
{
         NSLog(@收到html传过来的参数:str1=%@,str2=%@,str1,str2);
}
@end

3、在html页面中使用js代码调用该方法并传递2个参数(可以带中文),并使用button控件点击事件触发js方法。注意由于参数可能带有中文,故该html代码中应该有将中文转为utf-8的方法。html页面完整代码如下:

 

 

?
1
 
<script type=text/javaScript> function testClick(cmd) { //var str1 = ducument.getElementById(text1).value; //var str2 = ducument.getElementById(text2).value; var str1=document.getElementById(text1).value; var str2=document.getElementById(text2).value; //var str1=我来自ios苹果; //%25u6211%25u6765%25u81EAios%25u82F9%25u679C //var str2=我来自earth地球;//%25u6211%25u6765%25u81EAearth%25u5730%25u7403 document.write(Date()); window.location.href=objc://+cmd+:/+EncodeUtf8(str1)+:/+EncodeUtf8(str2); } // 字符串转换utf-8 function EncodeUtf8(s1) { // escape函数用于对除英文字母外的字符进行编码。如“Visit W3School!”->Visit%20W3School%21 var s = escape(s1); var sa = s.split(%);//sa[1]=u6211 var retV =; if(sa[0] != ) { retV = sa[0]; } for(var i = 1; i < sa.length; i ++) { if(sa[i].substring(0,1) == u) { retV += Hex2Utf8(Str2Hex(sa[i].substring(1,5))); if(sa[i].length>=6) { retV += sa[i].substring(5); } } else retV += % + sa[i]; } return retV; } function Str2Hex(s) { var c = ; var n; var ss = 0123456789ABCDEF; var digS = ; for(var i = 0; i < s.length; i ++) { c = s.charAt(i); n = ss.indexOf(c); digS += Dec2Dig(eval(n)); } //return value; return digS; } function Dec2Dig(n1) { var s = ; var n2 = 0; for(var i = 0; i < 4; i++) { n2 = Math.pow(2,3 - i); if(n1 >= n2) { s += '1'; n1 = n1 - n2; } else s += '0'; } return s; } function Dig2Dec(s) { var retV = 0; if(s.length == 4) { for(var i = 0; i < 4; i ++) { retV += eval(s.charAt(i)) * Math.pow(2, 3 - i); } return retV; } return -1; } function Hex2Utf8(s) { var retS = ; var tempS = ; var ss = ; if(s.length == 16) { tempS = 1110 + s.substring(0, 4); tempS += 10 + s.substring(4, 10); tempS += 10 + s.substring(10,16); var sss = 0123456789ABCDEF; for(var i = 0; i < 3; i ++) { retS += %; ss = tempS.substring(i * 8, (eval(i)+1)*8); retS += sss.charAt(Dig2Dec(ss.substring(0,4))); retS += sss.charAt(Dig2Dec(ss.substring(4,8))); } return retS; } return ; } </script>

4、在ViewController的viewDidLoad方法中加载该html网页:

 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
- ( void )viewDidLoad
{
     [ super viewDidLoad];
     webView.backgroundColor = [UIColor clearColor];
     //webView.scalesPageToFit =YES;
     webView.delegate =self;
     NSString *basePath = [[NSBundle mainBundle]bundlePath];
     NSString *helpHtmlPath = [basePath stringByAppendingPathComponent: @jsIOS .html];
     NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
     NSURLRequest *request=[NSURLRequest requestWithURL:url];
     [webView loadRequest:request];
}

5、在ViewCotroller中重写WebView的委托方法shouldStartLoadWithRequest:navigationType:,并接收html网页传递过来的2个参数:

 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
     NSString *urlString = [[request URL] absoluteString];
     urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSLog( @urlString =%@,urlString);
     NSArray *urlComps = [urlString componentsSeparatedByString:@: //];
     
     if ([urlComps count] && [[urlComps objectAtIndex: 0 ] isEqualToString: @objc ])
     {
         
         NSArray *arrFucnameAndParameter = [(NSString*)[urlComps objectAtIndex: 1 ] componentsSeparatedByString:@:/];
         NSString *funcStr = [arrFucnameAndParameter objectAtIndex: 0 ];
         
         if ( 1 == [arrFucnameAndParameter count])
         {
             // 没有参数
             if ([funcStr isEqualToString: @doFunc1 ])
             {
                 
                 /*调用本地函数1*/
                 NSLog( @doFunc1 );
                 
             }
         }
         else
         {
             //有参数的
             if ([funcStr isEqualToString: @getParam1 :withParam2:])
             {
                 [self getParam1:[arrFucnameAndParameter objectAtIndex: 1 ] withParam2:[arrFucnameAndParameter objectAtIndex: 2 ]];
             }
         }
         return NO;
     }
     return TRUE;
}

6、运行项目,点击网页中的按钮,即可实现html调用并传递参数给OC代码。

 

 

以下是完整的ViewController.m的代码:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
//  ViewController.m
//  JS_IOS_01
//
//  Created by IMAC on 14-2-24.
//  Copyright (c) 2014年 Wanggsx. All rights reserved.
//
 
# import ViewController.h
 
@interface ViewController ()
 
@end
 
@implementation ViewController
@synthesize webView;
- ( void )viewDidLoad
{
     [ super viewDidLoad];
     webView.backgroundColor = [UIColor clearColor];
     //webView.scalesPageToFit =YES;
     webView.delegate =self;
     NSString *basePath = [[NSBundle mainBundle]bundlePath];
     NSString *helpHtmlPath = [basePath stringByAppendingPathComponent: @jsIOS .html];
     NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
     NSURLRequest *request=[NSURLRequest requestWithURL:url];
     [webView loadRequest:request];
}
 
- ( void )didReceiveMemoryWarning
{
     [ super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
}
 
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
     NSString *urlString = [[request URL] absoluteString];
     urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSLog( @urlString =%@,urlString);
     NSArray *urlComps = [urlString componentsSeparatedByString:@: //];
     
     if ([urlComps count] && [[urlComps objectAtIndex: 0 ] isEqualToString: @objc ])
     {
         
         NSArray *arrFucnameAndParameter = [(NSString*)[urlComps objectAtIndex: 1 ] componentsSeparatedByString:@:/];
         NSString *funcStr = [arrFucnameAndParameter objectAtIndex: 0 ];
         
         if ( 1 == [arrFucnameAndParameter count])
         {
             // 没有参数
             if ([funcStr isEqualToString: @doFunc1 ])
             {
                 
                 /*调用本地函数1*/
                 NSLog( @doFunc1 );
                 
             }
         }
         else
         {
             //有参数的
             if ([funcStr isEqualToString: @getParam1 :withParam2:])
             {
                 [self getParam1:[arrFucnameAndParameter objectAtIndex: 1 ] withParam2:[arrFucnameAndParameter objectAtIndex: 2 ]];
             }
         }
         return NO;
     }
     return TRUE;
}
 
-( void )getParam1:(NSString*)str1 withParam2:(NSString*)str2
{
         NSLog(@收到html传过来的参数:str1=%@,str2=%@,str1,str2);
}
@end

你可能感兴趣的:(ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例))