Search code examples
htmliosnsdocumentdirectory

iOS: read html files from document directory


I have book folder in document directory. In this folder there are many html files, css and js. I wish to read each html file one by one from this folder.

How do I read each html file from documents directory in specific order- each html page represents each page of the book.

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?


Solution

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