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

时间:2014-04-23 08:36:19

标签: html ios nsdocumentdirectory

我在文档目录中有book个文件夹。在这个文件夹中有许多html文件,css和js。我希望从这个文件夹中逐个阅读每个html文件。

如何按特定顺序从文档目录中读取每个html文件 - 每个html页面代表书籍的每一页。

这是我到目前为止所做的:

- (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);
}

我该怎么做?

2 个答案:

答案 0 :(得分:2)

通过以下方式阅读文件:

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);
          }
     }

答案 1 :(得分:0)

试试这个,

    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]];
    }

如果文档目录中有任何css,此代码也可以使用。而且我建议你使用UIPageController和viewcontroller以及webview。