我有一个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
2015-03-25
KGNZ
+0
使用委托,当错误出现,加载本地HTML网页... –
2015-03-25 06:39:27
+0
您可以尝试https://github.com/rnapier/RNCachingURLProtocol –
2015-03-25 06:42:14
578

被折叠的 条评论
为什么被折叠?



