downloading files using UI web view - iphone

Is it possible to download files implementing UI web iphone in my app? If so where would the files be stored and how can I access it?

You can't really download files simply by browsing to them but what you could do is use
(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
to analyze the link for a file (say by looking at the extension of last path component) and if you want this kind of file to be downloaded than you could use [NSURLConnection connectionWithRequest:myURLRequest delegate:self]; and all its associated delegate methods to download and store the file in the documents folder.

if you want to visualize some known for webview file, it will show you automatically...but if page give back an unknown for webview file (This happened to me with Citrix ica file) webview will give you an error....to solve this problem i used this code (note that here i will allow to download only ica file, but you can change this condition):
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
if([error code]!=102)
{ [self.lblError setText:[NSString stringWithFormat:#"%#",error]];
return;
}
NSDictionary *userInfo = [error userInfo];
NSString * url = [[NSString alloc] initWithFormat:#"%#",[userInfo objectForKey:#"NSErrorFailingURLKey"] ];
NSString *search = #"?";
NSRange result = [url rangeOfString:search];
NSInteger startingPosition;
NSString *fileName,*fileExtention,*fileLocation;
if (result.location != NSNotFound) {
startingPosition = result.location + result.length;
fileLocation = [url substringToIndex:result.location];
fileExtention=[fileLocation pathExtension];
}
else
{
fileLocation=url;
}
fileName = [fileLocation lastPathComponent];
fileExtention=[fileLocation pathExtension];
//check if file to download if ica file
if(![fileExtention isEqualToString:#"ica"])
return;
self.lblError.textColor=[UIColor blackColor];
self.lblError.text=[NSString stringWithFormat:#"downloading %#...",fileName];
NSURL * _url = [[NSURL alloc] initWithString:url];
// Get file online
NSData *fileOnline = [[NSData alloc] initWithContentsOfURL:_url];
// Write file to the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
// NSLog(#"Documents directory not found!");
return;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
//NSLog(#"appFile path: %#",appFile);
[fileOnline writeToFile:appFile atomically:YES];
NSURL* aUrl = [NSURL fileURLWithPath:appFile];
self.interactionController = [UIDocumentInteractionController interactionControllerWithURL: aUrl];
self.interactionController.delegate = self;
self.lblError.text=[NSString stringWithFormat:#"%# downloaded",fileName];
[self.interactionController presentOpenInMenuFromRect:self.lblError.frame inView:self.view animated:YES];
}

Related

Can't get the path of the file

The code was working 100% but after shifting to iOS7 and XCode 5 I can't get the path of the file using NSFilemanager methods, the code can't find the path to timetableXML file and triggers -> else #"NO such a file exist", Here is there code:
- (void)viewDidLoad
{
[super viewDidLoad];
APUAppDelegate *appDelegate = (APUAppDelegate *)[[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
NSLog(#"Beginning download");
NSString *stringURL = #"http://webspace.apiit.edu.my/intake-timetable/download_timetable/timetableXML.zip";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSLog(#"Got the data!");
//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
//Save the data
NSLog(#"Saving");
dataPath = [path stringByAppendingPathComponent:#"timetableXML.zip"];
dataPath = [dataPath stringByStandardizingPath];
[urlData writeToFile:dataPath atomically:YES];
/////////////////// TEST
// Existence of the xml file
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathToMyFile = [path stringByAppendingPathComponent:#"timetableXML.zip"];
if ([fileManager fileExistsAtPath:pathToMyFile]) {
// file exists
NSLog(#"YES a file exist with ZIP extension");
NSLog(#"Unziped successfully!");
path1 = pathToMyFile;
[self unzipFile:path1];
}
else {
NSLog(#"NO such a file exist");
}
});
}
When writing the file the path is created with this code:
dataPath = [path stringByAppendingPathComponent:#"timetableXML.zip"];
dataPath = [dataPath stringByStandardizingPath];
but when testing the path is created with this code which is not the same:
NSString *pathToMyFile = [path stringByAppendingPathComponent:#"timetableXML.zip"];
NSLog() both paths and try to find the problem.
Look and see if the file was written.
Note, there there was no check of the status of the writeToFile: method, add that error check.

How to open Pdf file in different option like as iBook ,Go Daddy etc and save there in iPhone device?

In one Of my activity I have generated pdf file on WebView and save this file in document folder successfully but this file path show for simulator then get pdf file easily, but when we run my application on iPhone simulator then file show on device successfully and give file path but I can't find file where it save how to get this file open another problem I am using this code.
NSMutableData *data2 = [[NSMutableData alloc] initWithCapacity:byteArray.count];
for (NSNumber *byteVal in self.WebService->byteArray)
{
Byte b = (Byte)(byteVal.intValue);
[data2 appendBytes:&b length:1];
}
NSString *resourceToPath = [[NSString alloc]initWithString:[[[[NSBundle mainBundle]resourcePath]stringByDeletingLastPathComponent]stringByAppendingPathComponent:#"Documents"]];
fileName = [resourceToPath stringByAppendingPathComponent:#"myPDF.pdf"];
[data2 writeToFile:fileName atomically:YES];
NSURL *targetURL = [NSURL fileURLWithPath:fileName];
NSURLRequest *requestFile = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView1=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
webView1.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight) ;
webView1.scalesPageToFit = YES;
webView1.scrollView.scrollEnabled =NO;
[webView1 loadRequest:requestFile];
[self.view addSubview:webView1];
for download pdf file I am using this.....
-(void)DownloadPdffile
{
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *filePAth = [docDirectory stringByAppendingPathComponent:#"myPDF.pdf"];
NSURL *url2 = [NSURL filePAth];
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
docContr.delegate=self;
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
Using this code I've saved Pdf file in simulator successfully but in iPhone device I can't find where is my Pdf file and then using download pdf then .....this image open....!
But when I tapped any one of option then my application is closed so tell me how to open pdf in these option and save there also
If I understand what you are asking correctly, you need to refer to your documents folder differently in your -(void)DownloadPdffile method. Like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *pdfFilePath [documentsDir stringByAppendingPathComponent:yourPdfFile.pdf];// your yourPdfFile file here
NSURL *url = [NSURL fileURLWithPath:pdfPath];
UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:url];
docController.delegate = self;
[docController retain];
// docController is released when dismissed (autorelease in the delegate method)
BOOL isValid = [docController presentOpenInMenuFromRect:yourReadPdfButton.frame inView:self.view animated:YES]; // Provide where u want to read pdf from yourReadPdfButton
(from Prince's answer)

UIDocumentInteractionController Controller issues

i want to download pdf file from webservice and open it with UIDocumentInteractionController.how can i do it? i use following code for download
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"myurl/abc.pdf"]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"abcd.pdf"];
pdfData writeToFile:filePath atomically:YES];
now what should i do to open it with UIDocumentInteractionController
you can open PDF in UIDocumentInteractionController using bellow code This is a example of displaying pdf from NSBundle you can also displaying from Document directory like same as we display images. You need to full path of document and convert it into NSURL using fileURLWithPath:-
In yourViewController.h file:-
#interface yourViewController : UIViewController<UIDocumentInteractionControllerDelegate>
{
UIDocumentInteractionController *documentationInteractionController;
}
In **yourViewController.m file:-**
-(void) viewDidAppear:(BOOL)animated {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"abcd.pdf"];
NSURL *pdfUrl = [NSURL fileURLWithPath:filePath];
documentationInteractionController = [UIDocumentInteractionController interactionControllerWithURL:pdfUrl];
documentationInteractionController.delegate = self;
[documentationInteractionController presentPreviewAnimated:YES];
[super viewDidAppear:animated];
}
Delegate of UIDocumentInteractionController
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
return self;
}
Demo link
happy coding... :)

UIWebView displays locally stored document on simulator but not device

I have an issue where I'm trying to view a document (Word document, image, or video) that I have stored locally. I'm using UIWebView and on the Simulator it works perfectly, but on the device, it's a blank screen (no errors thrown in console). Here's my code to view the document:
UIWebView *newWebView;
if (appDelegate.IS_IPAD)
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
}
else
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
newWebView.scalesPageToFit = YES;
[self setWebView: newWebView];
[newWebView release], newWebView = nil;
[[self webView] setDelegate: self];
[[self view] addSubview:[self webView]];
NSURL *nsURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
[[self webView] loadRequest:[NSURLRequest requestWithURL:nsURL]];
Here's how I'm saving the document locally before viewing. I do think the file is getting successfully saved on the device as it does on the simulator.
// Save the file on the device
NSURL *contentUrl = [NSURL URLWithString:selectedContent.contentUrl];
NSString *fileName = [[contentUrl absoluteString] lastPathComponent];
NSString *homeDirectoryPath = NSHomeDirectory(); // Create the path
NSString *unexpandedPath = [homeDirectoryPath stringByAppendingString:#"/MyApp/"];
NSString *folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
NSString *unexpandedImagePath = [folderPath stringByAppendingFormat:#"/%#", fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL])
{
[[NSFileManager defaultManager] createDirectoryAtPath:nil withIntermediateDirectories:NO attributes:nil error:nil];
}
// Do the actual write of the file to the device
NSData *fileData = [NSData dataWithContentsOfURL:myUrl]; // Create the file data reference
[fileData writeToFile:filePath atomically:YES]; //Save the document to the home directory
Watch out for case issues. The simulator is not case sensitive whereas the iPhone is!
I solved this by saving my document to the default Documents Directory. Here's the code I used to accomplish this:
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [arrayPaths objectAtIndex:0];
NSString *filePath = [docDirectory stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSData *fileData = [NSData dataWithContentsOfURL:myUrl];
[fileData writeToFile:filePath atomically:YES];

download multiple files on iphone

i want to download file(s) from web server.
Scenario:
As user will select row (file name- user can select 1 or more files to download) and and press download, i am getting URL for each file(all have different URL) and storing into pathArray.
and doing following
-(void)downloadFile {
for (int i = 0; i<[pathArray count]; i++) {
NSURL *fileURL = [NSURL fileURLWithPath:[pathArray objectAtIndex:i]];
NSString *ResultURL = [fileURL absoluteString];
NSURL *url = [[NSURL alloc] initWithString:ResultURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 60.0];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {
NSLog(#"*************CONNECTED************");
webData = [[NSMutableData data] retain];
NSLog(#"weblength : %d : ", [webData length]);
downloadTag = YES;
} else {
NSLog(#"*************Connection NOT DONE************");
downloadTag=NO;
}
}
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"*************Try to receive data************");
[webData appendData:data];
NSLog(#"weblength : %d : ", [webData length]);
NSLog(#"*************Data Received an append too ***********");
if (downloadTag == YES) {
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
self.documentsDir = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"NewResult.zip" ];
[[NSFileManager defaultManager] createFileAtPath:documentsDir contents:nil attributes:nil];
NSFileHandle *file1 = [NSFileHandle fileHandleForUpdatingAtPath: documentsDir];
[file1 writeData: webData];
NSLog(#"Webdata : %d",[webData length]);
[file1 closeFile];
}
}
if i am not using for loop i.e only one file download then it work fine but not with for loop....its really important for me to solve this issue.
thank you very much
take a look at ASIHTTPRequest, it has a nice queue for downloading and monitoring progress http://allseeing-i.com/ASIHTTPRequest/How-to-use
You're using asynchronous downloads, but the delegate for each download item is the same object, causing all of the downloaded data to get appended to the same file. The way I do it is to have a small Object (DownloadQueueItem) that is the delegate for a single download. When you download another file, you create a new DownloadQueueItem and it handles everything.
Edit:
Q: instead of %i putting by my self i am searching is there any way to create new file every time like if ""NewResult.zip" is exist then create "NewResult1.zip" and so on
A: You could do something like this:
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = #"NewResult%#.zip";
for (int i = 0; ; i++) {
NSString *filename = NULL;
if (i == 0) {
filename = [NSString stringWithFormat:filename, #""];
}
else {
filename = [NSString stringWithFormat:filename, [NSString stringWithFormat:#"%i", i]];
}
if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) {
// Save file.
break;
}
}