下面的代码在启动时将 Word .docx 文件保存到应用程序的文档目录中。然后它在 viewDidLoad 期间将该文件读入 UIWebView。最后,它在从 UIWebView 获取文本之前等待 UIWebView 加载文档。不要忘记在视图控制器的头文件中遵守 UIWebViewDelegate 协议。当然,Word 文档必须包含在您的项目中。确保将文档添加到 Build Phases > Copy Bundle Resources。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/* WRITE WORD FILE TO DOCUMENT DIRECTORY */
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"Text.docx"];
NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/Text.docx"]];
[data writeToFile:path atomically:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
/* READ WORD FILE FROM DOCUMENT DIRECTORY TO WEB VIEW */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *wordFilePath = [documentsDirectory stringByAppendingPathComponent:@"Text.docx"];
UIWebView *theWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
NSURL *wordFileUrl = [NSURL fileURLWithPath:wordFilePath];
NSURLRequest *request = [NSURLRequest requestWithURL:wordFileUrl];
[theWebView loadRequest:request];
theWebView.delegate = self;
[self.view addSubview:theWebView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
/* GET TEXT FROM WEB VIEW */
NSString *text = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerText"];
}