Question

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?

Was it helpful?

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

OTHER TIPS

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. And also i would suggest you to use UIPageController with a viewcontroller and a webview.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top