I am having an app in which I am opening a PDF file from a url.
I am successfully able to open it in a webView.
Now I want to download that PDF file and sa
If convert to string server response, that you got in NSData *pdfData
, you will see next:
<!DOCTYPE html>
<html>
<head>
<title>iOS Developer Library</title>
<meta charset="utf-8">
<script>
var content_page = "navigation";
var href = window.location.href;
if (window.location.href.match('#')) {
var newhref = href.replace('#', '');
newhref = newhref.replace('%23', '#');
window.location.href = newhref;
}
else {
console.log(content_page);
console.log(content_page.match("content_page"));
if(content_page.match("content_page")) {
window.location.href = './navigation';
}
else {
window.location.href = "./" + content_page;
}
}
</script>
</head>
<body>
</body>
<script type="text/javascript" src="/library/webstats/pagetracker.js"></script>
<script type="text/javascript">
if(typeof PageTracker !== 'undefined') {
if(window.addEventListener) {
window.addEventListener("load", function(){PageTracker.logPageLoad()},false);
} else if(window.attachEvent) {
window.attachEvent("onload",function(){PageTracker.logPageLoad()});
}
}
</script>
</html>
This only web page, which, as I can assume, will forward you to document with another URI:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf
. So you must use this url if you want to download .pdf file
Also, pay attention on @pawan's answer, and use his approach to avoid download files in main thread
try this code for downloading & saving your pdf file
UIActivityIndicatorView *indicator=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator startAnimating];
NSLog(@"Downloading Started");
NSString *urlToDownload = @"http://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:120.0f];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[indicator stopAnimating];
if (!connectionError) {
if ( data )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"myfile.pdf"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[data
writeToFile:filePath atomically:YES];
NSLog(@"File Saved !");
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_rssWebView setUserInteractionEnabled:YES];
//[_rssWebView setDelegate:self];
[_rssWebView loadRequest:requestObj];
});
}
}
}];