如何在WebView Cocoa/Mac OS上加载带有images,js和css的本地html文件

Hot*_*day 11 macos cocoa webview

我有代码可以在iOS上运行.使用我在这里和网络上找到的任何东西,我设法在某个地方制作Cocoa Mac Os版本,但图像不会加载.CSS和Javascript似乎也没有加载.HTML的目录被添加到Resources组,但它被添加为Folder References(蓝色文件夹),这使得Xcode尊重HTML App的目录结构.

这是我正在尝试使用的代码:

NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" 
                                                     ofType:@"html" 
                                                inDirectory:@"/Patient_eMMR_HTML5" ];
NSString *html = [NSString stringWithContentsOfFile:htmlPath 
                                           encoding:NSUTF8StringEncoding 
                                              error:nil];

[[webView mainFrame] loadHTMLString:html baseURL:[NSURL fileURLWithPath:
                                                   [NSString stringWithFormat:@"%@/Patient_eMMR_HTML5/", 
                                                   [[NSBundle mainBundle] bundlePath]]]];
Run Code Online (Sandbox Code Playgroud)

这是我使用上面使用的代码的代码的iOS版本:

NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" 
                                                     ofType:@"html" 
                                                inDirectory:@"/Patient_eMMR_HTML5" ];

NSString *html = [NSString stringWithContentsOfFile:htmlPath 
                                           encoding:NSUTF8StringEncoding 
                                              error:nil];

[webView loadHTMLString:html 
                baseURL:[NSURL fileURLWithPath:
                         [NSString stringWithFormat:@"%@/Patient_eMMR_HTML5/", 
                          [[NSBundle mainBundle] bundlePath]]]];
Run Code Online (Sandbox Code Playgroud)

任何帮助是极大的赞赏.谢谢.

Rob*_*ger 14

如果您通过NSURLRequest而不是字符串加载HTML,则无需使用基本URL :

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"index" 
                                                     ofType:@"html"
                                                inDirectory:@"Patient_eMMR_HTML5"];
NSURL* fileURL = [NSURL fileURLWithPath:filePath];
NSURLRequest* request = [NSURLRequest requestWithURL:fileURL];
[[webView mainFrame] loadRequest:request];
Run Code Online (Sandbox Code Playgroud)

请注意,您应仅在?pathForResource:…方法中指定目录名称,不要在其前面添加正斜杠.假设命名目录以root包的目录为根.

请注意,UIWebView还有一个?loadRequest:方法,因此您可以在iOS上使用几乎相同的代码.