UIWebView 怎么才能载入包内文件或URL地址?


在 Cocoa 里,我通过 UI 工具,创建了一个 UIWebView
现在我想在 UIWebView 中载入一段内容,并且需求如下
1. 在 WebView 中载入包内 html 文件,
2. 或网络上的 url,
3. 某些情况下,我还想将一段字符串,直接写入 webView

xcode ios cocoa objective-c

Akira海 12 years, 3 months ago

大体说来,给 UIWebView 添加内容的方式分两种,
一种是从一个文件加载,类似在浏览器上输入URL或本地文件路径
一种是将一段 HTML 原代码,直接赋给 UIWebView

这些代码都是放在 IpadWebViewViewController.m 中:
1. 从URL上加载内容到 UIWebView

   
  #import "IpadWebViewViewController.h"
  
@implementation IpadWebViewViewController
@synthesize MyWebview;
// 程序主流程
- (void)viewDidLoad {
// 初始化
[[UIApplication sharedApplication] statusBarOrientation];
[super viewDidLoad];
// 从 URL 中载入一个 html 页面
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
[self.MyWebview loadRequest:[NSURLRequest requestWithURL:url]];
}

2. 从APP 包内读取加载一个 HTML 文件

   
  #import "IpadWebViewViewController.h"
  
@implementation IpadWebViewViewController
@synthesize MyWebView;
// 程序主流程
- (void)viewDidLoad {
// 初始化
[[UIApplication sharedApplication] statusBarOrientation];
[super viewDidLoad];
// 从 APP 包内 载入一个 html 页面
NSString *htmlPath = [[[NSBundle mainBundle] bundlePath]
stringByAppendingPathComponent:@"webapp/index.html"];
// NSString *htmlPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"webapp/index.html"];
[self.MyWebview loadRequest:[NSURLRequest requestWithURL:[NSURL
fileURLWithPath:htmlPath]]];
}

3.直接在 UIWebView 中写入一段 HTML 代码。
htmlPath 似乎是一个必须的参数,而 htmlString 是可以可以直接写成

   
  NSString *htmlString = @”<html ….”;
 

不是必须从一个文件来获取 HTML 串的。

   
  #import "IpadWebViewViewController.h"
  
@implementation IpadWebViewViewController
@synthesize MyWebview;
// 程序主流程
- (void)viewDidLoad {
// 初始化
[[UIApplication sharedApplication] statusBarOrientation];
[super viewDidLoad];
// 读入一个 HTML
NSString *htmlPath = [[[NSBundle mainBundle] bundlePath]
stringByAppendingPathComponent:@"webapp/loader.html"];
NSString *htmlString = [NSString stringWithContentsOfFile: htmlPath
encoding:NSUTF8StringEncoding error:NULL];
[self.MyWebview loadHTMLString:htmlString baseURL:[NSURL
fileURLWithPath:htmlPath]];
}

伪LOLI控 answered 12 years, 3 months ago

Your Answer