[IOS]UIWebView 請求網路頁面或者載入本地資源頁面
阿新 • • 發佈:2019-02-02
UIWebView是一個能夠顯示網頁的IOS檢視控制元件,我們可以用它來訪問一個網站。下面是具體的例項:
操作步驟:
1.首先在xib檔案中拖放一個UIWebView控制元件到view中
2.將下載的頁面以及頁面資源載入到專案中,但必須選擇Create folder references for any added folders,然後知道檔案在專案中是藍色顯示,而不是黃色顯示
3.將webView的Delegate拖到File's Owner,繼承UIWebView的Delegate協議,並且實現他的協議
ViewController.h:
#import <UIKit/UIKit.h> @interface DXWViewController : UIViewController<UIWebViewDelegate> @property (retain, nonatomic) IBOutlet UIWebView *webview; @property(nonatomic,retain) UIAlertView *alert; @end
ViewController.m:
#import "DXWViewController.h" @interface DXWViewController () @end @implementation DXWViewController - (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; //[self.webview loadRequest:request]; //載入本地資源,html頁面 NSString *str = [[NSBundle mainBundle] pathForResource:@"百度圖片—全球最大中文圖片庫" ofType:@"html"]; str = [NSString stringWithContentsOfFile:str encoding:NSUTF8StringEncoding error:nil]; NSLog(@"%@",str); [self.webview loadHTMLString:str baseURL:[[NSBundle mainBundle] bundleURL]]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)dealloc { [_webview release]; [_alert release]; [super dealloc]; } -(void)webViewDidFinishLoad:(UIWebView *)webView { [self.alert dismissWithClickedButtonIndex:0 animated:YES]; } -(void)webViewDidStartLoad:(UIWebView *)webView { self.alert = [[UIAlertView alloc] initWithTitle:@"Loading..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil]; [self.alert show]; UIActivityIndicatorView *aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; aiv.center = CGPointMake(self.alert.bounds.size.width/2, self.alert.bounds.size.height/2); [aiv startAnimating]; [self.alert addSubview:aiv]; } @end