iOS开发——网络编程OC篇&使用WebView构建HyBird应用

时间:2021-03-11 12:27:55

使用WebView构建HyBird应用

HyBird是一种本地技术与Web相结合,能过实现跨平台的移动应用开发,最常用的一个框架:PhoneGap

一:首先,写好html代码

 <!DOCTYPE html>
 <html>
     <head>
         <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
         <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
         <script>
             //从iOS对象中调用
             function  helloWorld(msg) {
                 document.getElementById('message').innerHTML = msg;
             }
             //调用iOS对象
             function showAndroidDialog(msg) {
                 var myJSONObject = new Object();
                 myJSONObject.title = 'HelloWorld';
                 myJSONObject.message = msg;
                 var JSONString = JSON.stringify(myJSONObject);
                 var uri = 'gap://XXXClass.XXXmethod#' + JSONString;
                 window.location = uri;
             }
          </script>

     </head>
     <body>
         <h2>iOS本地与Web互相调用</h2>
         <button onclick='showAndroidDialog("JS to iOS 对象")'>调用iOS对象</button>
         <br><br>
         <div  id='message'></div>
     </body>
 </html>

二:在iOS中调用javaScript代码:

 - (void)viewDidLoad
 {
     [super viewDidLoad];
     // Do any additional setup after loading the view, typically from a nib.

     self.webView.delegate = self;
     NSString *path = [[NSBundle mainBundle] pathForResource:@"www/index" ofType:@"html"];
     [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];
 }

 - (void)didReceiveMemoryWarning
 {
     [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
 }

 #pragma mark UIWebViewDelegate

 - (void)webViewDidFinishLoad:(UIWebView *)webView
 {
     [self.webView stringByEvaluatingJavaScriptFromString:@"helloWorld('从iOS对象中调用JS Ok.')"];
 }

 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
 {
     NSString *actionType = request.URL.host;
     NSString *scheme = request.URL.scheme;
     NSString *fragment = [request.URL.fragment URLDecodedString];
     NSData *responseData = [fragment dataUsingEncoding:NSUTF8StringEncoding];

     if ( [scheme isEqualToString:@"gap"] ) {
         if ([actionType isEqualToString:@"XXXClass.XXXmethod"]) {

             NSError* error;
             NSDictionary* json = [NSJSONSerialization
                                   JSONObjectWithData:responseData
                                   options:NSJSONReadingAllowFragments
                                   error:&error];

             NSLog(@"title: %@ , message: %@",[json objectForKey:@"title"], [json objectForKey:@"message"] );

         }
     }
     return true;
 }

注:这里用到了一个NSString的分类用于字符串雨URL的编码与解码

 - (NSString *)URLEncodedString
 {
     NSString *result = (NSString *)
     CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                             (CFStringRef)self,
                                             NULL,
                                             CFSTR("!*'();:@&amp;=+$,/?%#[] "),
                                             kCFStringEncodingUTF8));
     return result;
 }

 - (NSString*)URLDecodedString
 {
     NSString *result = (NSString *)
     CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
                                                             (CFStringRef)self,
                                                             CFSTR(""),
                                                             kCFStringEncodingUTF8));
     return result;
 }

WebView 总结:

一:网页加载
1:回退和前进

//    if ([webView canGoBack]) {
//        self.backItem.enabled = YES;
//    } else {
//        self.backItem.enabled = NO;
//    }
self.backItem.enabled = [webView canGoBack];
self.forwardItem.enabled = [webView canGoForward];

self.backItem.enabled = [webView canGoBack];
self.forwardItem.enabled = [webView canGoForward];

2:字符串查找
// 如果在path中找不到@“baidu”这个字符串
//    [path rangeOfString:@"baidu"].length == 0;
//    [path rangeOfString:@"baidu"].location == NSNotFound

// URL格式:协议头://主机名/路径
// request.URL.path : 获得的仅仅是主机名(域名)后面的路径
// request.URL.absoluteString : 获得的是一个完整的URL字符串

// 1.获得完整的url字符串
NSString *url = request.URL.absoluteString;
NSUInteger loc = [url rangeOfString:@"baidu"].location;

// 2.找到baidu字符串,返回NO
if (loc != NSNotFound) { // 能找到
    return NO; // 禁止加载
}

// 3.如果没有找到,返回YES
return YES;

//    return loc == NSNotFound ? YES : NO;
//    return loc == NSNotFound;