繁体   English   中英

从Xcode中的数组加载本地HTML

[英]Loading local html from an array in xcode

我正在尝试从数组将本地托管的html文件加载到webview中。 它看起来像这样

_siteAddresses = [[NSArray alloc]
                      initWithObjects:@"file://localhost/var/mobile/Application/${APP_ID}/First Pentecostal Seminary.app/First_Pentecostal_Seminary/Main.html",...

对应的代码是

NSString *urlString = [_siteAddresses
                       objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

self.detailViewController.webView.scalesPageToFit = YES;

[self.detailViewController.webView loadRequest:request];

我在做什么错...是我的编码还是html编码(我相信里面可能有一些Java)

两个想法:

  1. 该示例文件URL看起来不正确。 您是如何构建的? 如果是您设备上的捆绑包中的某件东西,那么我希望它更像是:

     file:///var/mobile/Applications/9E670C3C-C8B1-4B09-AE66-B43F7DB29F4D/First Pentecostal Seminary.app/... 

    显然,您必须使用NSBundle实例方法URLForResource或使用捆绑软件的bundleURL ,然后添加适当的路径组件,以编程方式确定此URL。

  2. 您应该(a)指定视图控制器为您的Web视图的delegate 然后(b)实施webView:didFailLoadWithError:并查看其中的错误,它将通知您错误是什么(如果有)。


例如,我的文件包中有一个文件test.html ,可以将其加载到Web视图中,如下所示:

NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSURL *url = [bundleURL URLByAppendingPathComponent:@"test.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

我已经将视图控制器设置为Web视图的委托,并具有以下didFailLoadWithError

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"%s: %@", __FUNCTION__, error);
}

因此,当我这次尝试使用无效的URL( test2.html ,但我的捆绑包中没有)加载请求时,出现以下错误:

2014年2月26日23:35:43.593 MyApp [3531:70b]-[ViewController webView:didFailLoadWithError:]:错误域= NSURLErrorDomain代码= -1100“在此服务器上找不到请求的URL。” UserInfo = 0x8c32f40 {NSErrorFailingURLStringKey = file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFFFF/MyApp.app/test2.html,NSErrorFailingURLKey = file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFFFF/MyApp.app/test2.html,NSLocalizedDescription =请求的URL是在此服务器上找不到。,NSUnderlyingError = 0xx10424c90“在此服务器上找不到请求的URL。”}

Try this code   

UIWebView *documentsWebView=[[UIWebView alloc]init];
documentsWebView.delegate=self;
documentsWebView.frame=CGRectMake(0, 0, 1024, 616);  
documentsWebView.backgroundColor=[UIColor clearColor];  
[self.view addSubview:documentsWebView];    
NSString* htmlString = [NSString stringWithContentsOfFile:[_siteAddresses
                   objectAtIndex:indexPath.row] encoding:NSUTF8StringEncoding error:nil];  
[documentsWebView loadHTMLString:htmlString baseURL:nil];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM