Objective-C Learning Notes - UIWebView4(坑)
在 iOS 应用中,当使用 UIWebView 控件在屏幕中显示指定的网页后,我们可以通过触摸的方式浏览指定的网页.
在具体实现时,是通过 webView:shouldStartLoadWithRequest:navigationType 方法来实现的.
其中 NavigationType 包括如下所示的可选参数值:
UIWebViewNavigationTypeLinkClick //链接被触摸时请求这个链接
UIWebViewNavigationTypeFormSubmitted //form 被提交时请求这个 form 的内容
UIWebViewNavigationTypeBackForward //当通过 goBack 或者 goForward进行页面转移时移动目标 URL
UIWebViewNavigationTypeReload //当页面重新导入时导入这个 URL
UIWebViewNavigationTyoeOrther //使用 loadRequest 方法读取内容
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (strong,nonatomic) UIWebView *myWebView; @end
#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize myWebView; - (void)viewDidLoad { [super viewDidLoad]; myWebView = [[UIWebView alloc]init]; myWebView.frame = self.view.bounds; myWebView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; [self.view addSubview:myWebView]; // Do any additional setup after loading the view, typically from a nib. } - (void)loadHTMLFile:(NSString *)path{ NSArray *components = [path pathComponents]; NSString *resourceName = [components lastObject]; NSString *abslutePath; if ((abslutePath = [[NSBundle mainBundle]pathForResource:resourceName ofType:nil])){ NSData *data = [NSData dataWithContentsOfFile:abslutePath]; [myWebView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:nil]; }else{ NSLog(@"%@ not found!", resourceName); } } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ if (UIWebViewNavigationTypeLinkClicked == navigationType){ NSString *url = [[request URL] path]; [self loadHTMLFile:url]; return NO; }else if(UIWebViewNavigationTypeFormSubmitted == navigationType){ NSString *url = [[request URL] path]; NSArray *components = [url pathComponents]; NSString *resultString = [webView stringByEvaluatingJavaScriptFromString:[components lastObject]]; UIAlertView *alert = [[UIAlertView alloc]init]; alert.message = resultString; [alert addButtonWithTitle:@"OK"]; [alert show]; return NO; } return YES; } - (void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; [self loadHTMLFile:@"./top.html"]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end