简体   繁体   English

iOS:从文档目录中读取html文件

[英]iOS: read html files from document directory

I have book folder in document directory. 我在文档目录中有book文件夹。 In this folder there are many html files, css and js. 在这个文件夹中有许多html文件,css和js。 I wish to read each html file one by one from this folder. 我希望从这个文件夹中逐个阅读每个html文件。

How do I read each html file from documents directory in specific order- each html page represents each page of the book. 如何按特定顺序从文档目录中读取每个html文件 - 每个html页面代表书籍的每个页面。

Here is what I have done so far: 这是我到目前为止所做的:

- (IBAction)btnRead_click:(id)sender {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSArray *filePathsArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];

    NSLog(@"files array %@", filePathsArray);
}

How do I do this? 我该怎么做呢?

Read the file by below way: 通过以下方式阅读文件:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     NSString *bookDirectoryPath = [documentsDirectory stringByAppendingPathComponent:@"book"];

    NSArray *fileNamesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bookDirectoryPath error:nil];

     for(NSString *fileName in fileNamesArray)
     {
          if([[fileName pathExtension] isEqualToString:@"html"])
          {
               NSError *err = nil;
               NSString *fileNamePath = [bookDirectoryPath stringByAppendingPathComponent:fileName];
               NSString *htmlContent = [NSString stringWithContentsOfFile:fileNamePath
                                                                 encoding:NSUTF8StringEncoding
                                                                    error:&err];
               NSLog(@"%@",htmlContent);
          }
     }

Try This, 尝试这个,

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *finalPath = [[documentsDirectory stringByAppendingPathComponent:fileName];

    if ([[NSFileManager defaultManager] fileExistsAtPath:finalPath]==NO)
    {
       NSLog(@"File Not Found");

    }
    else
    {
        NSData *htmlData = [NSData dataWithContentsOfFile:finalPath];
        [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:documentsDirectory isDirectory:YES]];
    }

This code will also work if you have any css in the documents directory. 如果文档目录中有任何css,此代码也可以使用。 And also i would suggest you to use UIPageController with a viewcontroller and a webview. 而且我建议你使用UIPageController与viewcontroller和webview。

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

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