How to download files from UIWebView and open again
Use the method - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
in your UiWebView's delegate to determine when it wants to load resource.
When the method get's called, you just need to parse the URL from the parameter (NSURLRequest *)request
, and return NO if it's one of your desired type and continue with your logic (UIActionSheet) or return YES if the user just clicked a simple link to a HTML file.
Makes sense?
Edit_: For better understanding a quick code example
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if(navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *requestedURL = [request URL];
// ...Check if the URL points to a file you're looking for...
// Then load the file
NSData *fileData = [[NSData alloc] initWithContentsOfURL:requestedURL;
// Get the path to the App's Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
[fileData writeToFile:[NSString stringWithFormat:@"%@/%@", documentsDirectory, [requestedURL lastPathComponent]] atomically:YES];
}
}
Edit2_: I've updated the code sample after our dicussion about your issues in the chat:
- (IBAction)saveFile:(id)sender {
// Get the URL of the loaded ressource
NSURL *theRessourcesURL = [[webView request] URL];
NSString *fileExtension = [theRessourcesURL pathExtension];
if ([fileExtension isEqualToString:@"png"] || [fileExtension isEqualToString:@"jpg"]) {
// Get the filename of the loaded ressource form the UIWebView's request URL
NSString *filename = [theRessourcesURL lastPathComponent];
NSLog(@"Filename: %@", filename);
// Get the path to the App's Documents directory
NSString *docPath = [self documentsDirectoryPath];
// Combine the filename and the path to the documents dir into the full path
NSString *pathToDownloadTo = [NSString stringWithFormat:@"%@/%@", docPath, filename];
// Load the file from the remote server
NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL];
// Save the loaded data if loaded successfully
if (tmp != nil) {
NSError *error = nil;
// Write the contents of our tmp object into a file
[tmp writeToFile:pathToDownloadTo options:NSDataWritingAtomic error:&error];
if (error != nil) {
NSLog(@"Failed to save the file: %@", [error description]);
} else {
// Display an UIAlertView that shows the users we saved the file :)
UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"File saved" message:[NSString stringWithFormat:@"The file %@ has been saved.", filename] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[filenameAlert show];
[filenameAlert release];
}
} else {
// File could notbe loaded -> handle errors
}
} else {
// File type not supported
}
}
/**
Just a small helper function
that returns the path to our
Documents directory
**/
- (NSString *)documentsDirectoryPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
return documentsDirectoryPath;
}
Downloading a file using web view
SwiftHTTP (https://github.com/daltoniam/swiftHTTP) made it possible to me!
Open downloaded files in iOS app
Try this
NSString* pdfFile = @""; //path of file here
NSURL *url = [NSURL fileURLWithPath:pdfFile];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[webView loadRequest:request];
[self.view addSubview:webView];
Downloading files from uiwebview in iphone sdk
You can provide webView:shouldStartLoadWithRequest
in your UIWebViewDelegate
so that each time the user is about to move to another web page, you have the chance to check what the link looks like:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] scheme] isEqual:@"http"] &&
[[[request URL] pathExtension]...])
<your download/save code here>
return NO; //-- no need to follow the link
}
return YES; //-- otherwise, follow the link
}
View Downloaded PDF on UIWebView
You code looks ok but the path is not
let downloadedFilePath = "///var/mobile/Containers/Data/Application/DBC9AFAB-3FD4-4D06-82F5-0577251001A7/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf"
let filePathURL = NSURL(fileURLWithPath: downloadedFilePath);
webView.loadRequest(NSURLRequest(URL: url));
Try this hope it works.
For checking that the file exist Open a new finder and press Command+Shift+G after that copy and paste the file path and press enter
If the file load then the file exist. File path in your case is " ///var/mobile/Containers/Data/Application/DBC9AFAB-3FD4-4D06-82F5-0577251001A7/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf "
Download PDF via UIWebView
-initWithContentsOfURL:
method of NSData
does a simple HTTP GET, but you needed to set some Authorization params that's why it fails.
To avoid downloading twice the data, you could use NSURLSession
to download it, save it, and use the -loadData:MIMEType:textEncodingName:baseURL:
of UIWebView
to load it.
NSMutableURLRequest *mutableRequest = //Your Custom request with URL and Headers
[[[NSURLSession sharedSession] dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
if (data)
{
//SaveDataIntoDisk
dispatch_async(dispatch_get_main_queue(), ^(){
[_webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];
});
}
}] resume];
How can I download files from UIWebView using ASIHTTPRequest?
ASIWebPageRequest is the answer. It's a class included with ASIHTTPRequest that makes it easy to download whole pages, with all their associated dependencies.
You'd probably want to create a custom cache to store your downloaded webpages in, and then load them out of that cache when requested by the user.
IOS - Download file then showing it on UIWebView
[[NSBundle mainBundle] URLForResource:file.nameWithoutExtension withExtension:@"pdf"]
will give you file from your xcode project folder.
Use this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"yourFileName.pdf"];
It will get you a file from Documents folder.
Related Topics
Set Rootviewcontroller of Uinavigationcontroller by Method Other Than Initwithrootviewcontroller
Show Current Location and Update Location in Mkmapview in Swift
Wkwebview and Nsurlprotocol Not Working
How to Split String into Substrings on iOS
Connect Outlet of a Cell Prototype in a Storyboard
How to Display the Standard Checkmark on a Uicollectionviewcell
Application Executable Is Missing a Required Architecture Armv6
Warning: Output of Vertex Shader 'V_Gradient' Not Read by Fragment Shader
Tracking Multiple (20+) Locations with iOS Geofencing
How to Dismiss the iOS Keyboard
Uitextview: Disable Selection, Allow Links
How to Open the Imagepicker in Swiftui
How to Manage Cookies with Uiwebview in Swift
Alamofire Download in Background Session
How to Call Method from Viewcontroller in Gamescene
How to Calculate Actual Font Point Size in iOS 7 (Not the Bounding Rectangle)