我有一個uiwebview
在我的應用程序,顯示服務器上承載的HTML文件的數量。如果沒有互聯網連接,我還想要顯示將顯示的html文件的本地副本,但我不知道如何執行此操作。我有的.m文件與下面類似。如何加載本地HTML文件,如果沒有互聯網連接
目前uiwebview
將顯示遠程託管的網頁(以下「contact.html」的例子。有沒有人能夠解釋,如果沒有可用的互聯網我如何加載該文件的本地副本?
#import "ContactMeViewController.h"
@interface ContactMeViewController()
@end
@implementation ContactMeViewController
- (void)viewDidLoad
{
NSString *urlAddress = @"http://www.domain.co.nz/apppages/contact.html";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webview loadRequest:requestObj];
webview.scalesPageToFit = YES;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
我已經更新了.m文件如下,卻得到了一個空白的屏幕,沒有互聯網連接,而不是本地文件加載:
#import "ContactMeViewController.h"
@interface ContactMeViewController (UIWebViewDelegate)
@end
@implementation ContactMeViewController
- (void)viewDidLoad
{
NSString *urlAddress = @"http://www.kuranimarsters.co.nz/apppages/contact.html";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webview loadRequest:requestObj];
webview.scalesPageToFit = YES;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if (-1009 == kCFURLErrorNotConnectedToInternet) {
// if we can identify the error i.e, no internet connection
[self loadHtmlFile];
}
}
-(void)loadHtmlFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"contact.html"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSString* htmlString = [NSString stringWithContentsOfFile:content encoding:NSUTF8StringEncoding error:nil];
[webview loadHTMLString:htmlString baseURL:nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
使用委託,當錯誤出現,加載本地HTML網頁... – 2015-03-25 06:39:27
您可以嘗試https://github.com/rnapier/RNCachingURLProtocol – PowHu 2015-03-25 06:42:14