Edoardo
Edoardo

Reputation: 65

Saving a PDF file through a UIWebView so that is visible (in the same WebView) even offline

I have this question that is driving me crazy: could I save a PDF file (that is online) locally on an iOS Device so that I can view the file every time even offline in the same UIWebView? If I could, how?

Upvotes: 0

Views: 2871

Answers (1)

Rafael Steil
Rafael Steil

Reputation: 4697

If you have control over such UIWebView and the URL it opens, then yes, you can. See the following code as example. It uses the ASIHttpRequest library, which you can find at http://allseeing-i.com/ASIHTTPRequest/

#import "WebViewPDFViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "ASIHTTPRequest.h"

@implementation WebViewPDFViewController

-(NSString *) md5:(NSString *) str {
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result );

    return [NSString stringWithFormat:
        @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
        result[0], result[1], result[2], result[3], 
        result[4], result[5], result[6], result[7],
        result[8], result[9], result[10], result[11],
        result[12], result[13], result[14], result[15]
    ];  
}

-(void) viewWillAppear:(BOOL)animated {
    NSString *pdfOnlinePath = @"http://redinter.eu/web/files/revistas/2Dummy.pdf";

    // Check if the file is already stored locally. If it is not, then first
    // download it, and load from the local cache. Next requests will always
    // load from the local cache
    NSString *pdfHash = [self md5:pdfOnlinePath];
    NSString *pdfCachePath = [NSString stringWithFormat:@"%@/pdfcache_%@.pdf", 
        [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0], 
        pdfHash];

    if ([[NSFileManager defaultManager] fileExistsAtPath:pdfCachePath]) {
        NSLog(@"Cached file found, using it");
    }
    else {
        // Not found in the local cache, download and store it
        NSLog(@"File  not found in the local cache, going to download it");
        ASIHTTPRequest *downloadRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:pdfOnlinePath]];
        [downloadRequest setDownloadDestinationPath:pdfCachePath];
        [downloadRequest startSynchronous];
    }

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfCachePath]];

    UIWebView *webView = [[[UIWebView alloc] initWithFrame:self.view.bounds] autorelease];
    [webView loadRequest:request];

    [self.view addSubview:webView];
}

- (void)dealloc {
    [super dealloc];
}

@end

I have tested it here ant it works fine.

Upvotes: 1

Related Questions