【发布时间】:2015-03-25 17:56:19
【问题描述】:
我的应用中有许多 uiwebview,它们显示托管在服务器上的 html 文件。如果没有互联网连接,我还想拥有将显示的 html 文件的本地副本,但我不明白该怎么做。我拥有的 .m 文件与下面类似。
目前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页面...