从NSHomeDirectory()在UIWebView中加载文件?

时间:2012-01-22 23:49:38

标签: objective-c uiwebview

如何从UIWebview中的NSHomeDirectory()加载文件?这是可能的 ?我的意思是从/ Documents /文件夹加载.pdf文件。

谢谢!

2 个答案:

答案 0 :(得分:1)

以下是如何在iphone应用程序中本地下载,阅读和存储您的PDF文件:

首先创建UIWebView并包含<< UIWebViewDelegate >>

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
  NSString *documentsPath = [paths objectAtIndex:0];
  NSString *filePath = [documentsPath stringByAppendingPathComponent:@"YourPDF.pdf"]; 
 if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
           // download file , here "https://s3.amazonaws.com/hgjgj.pdf" = pdf downloading link
         NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"https://s3.amazonaws.com/hgjgj.pdf"]];
            //Store the downloaded file  in documents directory as a NSData format
         [pdfData writeToFile:filePath atomically:YES];
    }

     NSURL *url = [NSURL fileURLWithPath:filePath];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     [yourWebView setUserInteractionEnabled:YES];
     [yourWebView setDelegate:self];
     yourWebView.scalesPageToFit = YES;
     [yourWebView loadRequest:requestObj];

或者,如果您只是想从资源文件夹中读取/加载pdf,那么只需执行以下操作:

     NSString*  filePath= [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"pdf"]];
    /// or you can even read docs file as : pathForResource:@"sample" ofType:@"docx"]
     NSURL *url = [NSURL fileURLWithPath:filePath];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     [yourWebView setUserInteractionEnabled:YES];
     [yourWebView setDelegate:self];
     yourWebView.scalesPageToFit = YES;
     [yourWebView loadRequest:requestObj];

答案 1 :(得分:0)

我不知道NSHomeDirectory()是如何工作的,但您可以查看this post以了解如何获取文件的完整路径以及this other以了解如何加载文件PDFUIWebView