Is there any way to download file from UIWebView i am using this code on my IBAction event
- (IBAction)saveFile:(id)sender {
// Get the URL of the loaded ressource
NSURL *theRessourcesURL = [[self.webDisplay request] URL];
NSString *fileExtension = [theRessourcesURL pathExtension];
if ([fileExtension isEqualToString:#"png"] || [fileExtension isEqualToString:#"jpg"] ||
[fileExtension isEqualToString:#"pdf"] || [fileExtension isEqualToString:#"html"]) {
// 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 {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"File could not be loaded"
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
// File could notbe loaded -> handle errors
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Warning"
message:#"File type not supported"
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
[alert release];
// File type not supported
}
}
this code open the file in UIWebView , which i want to download and when i press the button the opened file get save.
But i want my UIWebView to behave like normal browser , when the download link appear in it and user press it, UIWebView show dialog with option open it or save it if user press save the file get save automatically and if user press open it file should open in UIWebView.
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
}
Related
I have a static file path to a download folder, files download fine but when I download a new one the old one gets replaced by new. I suppose because of static pathing. How do I add a timestamp to my code so whenever a new download is made the old one wouldn't get replaced?Or maybe even give download file the "original" filename from the actual array?
here is my download code:
-(void) Savefile {
[self.downloadfile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Wooopss!" message:#"Download failed. Try Again..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else if (data) {
[data writeToFile:#"/Users/Danny/Desktop/PDFFile/hello.pdf" atomically:NO ];
NSLog(#"Downloading file...");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Downloading" message:#"File is being downloaded..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
}
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"MMddYYYYmmss"];
NSString *filePath = [NSString stringWithFormat:#"/Users/Danny/Desktop/PDFFile/hello_%#.pdf", [dateFormatter stringFromDate:[NSDate date]]];
Which will give you this:
/Users/Danny/Desktop/PDFFile/hello_032620144401.pdf
Not entirely sure what you mean by:
Or maybe even give download file the "original" filename from the
actual array
I have created a camera using AVFoundation, now i want my video back so i can upload it on my server how can i do that ?
I am using MKNetworkKit for upload video on server.
I am getting output like this:
file://localhost/private/var/mobile/Applications/4B2E02E5-3EE2-493E-8ECF-4B1DA29B9387/tmp/output.mov
Guys I have figured out it by some help here is code for that.
- (void) captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)anOutputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
videodata = [NSData dataWithContentsOfURL:outputFileURL];
//NSLog(#"output file url is :%#",anOutputFileURL);
NSLog(#"output video data size is:%d", videodata.length);
if ([[self delegate] respondsToSelector:#selector(recorder:recordingDidFinishToOutputFileURL:error:)]) {
[[self delegate] recorder:self recordingDidFinishToOutputFileURL:anOutputFileURL error:error];
}
//NSLog(#"captureOutput is: %#",captureOutput);
// NSLog(#"anOutputFileURL is: %#",anOutputFileURL);
//videoPath = [NSString stringWithContentsOfURL:anOutputFileURL encoding:NSUTF8StringEncoding error:nil];
//videoPath = [anOutputFileURL absoluteString];
//videoURL = anOutputFileURL;
// videodata = captureOutput;
// NSLog(#"video path is: %#",videodata);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
message:#"Do you want to upload this content to the yes stream network ?"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
NSLog(#"Yes was selected.");
self.flUploadEngine = [[fileUploadEngine alloc] initWithHostName:#"manektech.net" customHeaderFields:nil];
NSMutableDictionary *postParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"testApp", #"appID",
nil];
self.flOperation = [self.flUploadEngine postDataToServer:postParams path:#"/dilipvideotest/savefile.php"];
[self.flOperation addData:videodata forKey:#"uploadfile" mimeType:#"video/mov" fileName:#"output.mov" ];
[self.flOperation onCompletion:^(MKNetworkOperation *operation) {
NSLog(#"response string is : %#", [operation responseString]);
/*
This is where you handle a successful 200 response
*/
}
onError:^(NSError *error) {
NSLog(#"error : %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}];
[self.flUploadEngine enqueueOperation:self.flOperation ];
}
else if([title isEqualToString:#"No"])
{
NSLog(#"No was selected.");
//[self readMovie:outputFileURL];
}
}
I have set up some code so that when two separate buttons are tapped on a UIActionSheet, there will be two different actions. Unfortunately nothing happens when the buttons are pressed. The UIActionSheet just unloads as if a cancel button had been pressed.
Here's my code:
- (IBAction)saveFile:(id)sender {
UIActionSheet *saveFileSheet = [[[UIActionSheet alloc]
initWithTitle:#"iDHSB Download Centre"
delegate:nil
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Download File", #"Show My Files", nil]
autorelease];
[saveFileSheet showInView:webView];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(#"Action Sheet Button Pressed");
if(buttonIndex == 1) {
NSLog(#"Show My Files");
[self.window presentModalViewController:savedFiles animated:YES];
}
if(buttonIndex == 2){
NSLog(#"Saving File");
// Get the URL of the loaded ressource
NSURL *theResourcesURL = [[webView request] URL];
// Get the filename of the loaded ressource form the UIWebView's request URL
NSString *filename = [theResourcesURL 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:theResourcesURL];
// 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) {
UIAlertView *filenameErrorAlert = [[UIAlertView alloc] initWithTitle:#"Error Saving" message:[NSString stringWithFormat:#"The file %# could not be saved. Please try again.", filename] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[filenameErrorAlert show];
[filenameErrorAlert release];
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 {
NSLog(#"Error, file could not be saved");
}
}
else
{
NSLog(#"Error, could not find button index!");
}
}
Thanks,
James
You have set the UIActionSheet delegate to nil. In this context, you want to set it to self.
You have to set the delegate to self
UIActionSheet *saveFileSheet = [[[UIActionSheet alloc]
initWithTitle:#"iDHSB Download Centre"
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Download File", #"Show My Files", nil]
autorelease];
You’re creating the action sheet with a nil delegate, so the delegate methods you implemented will never get called. Pass self as the delegate in the action sheet’s initializer and it should work.
I have managed to get my app to upload to Dropbox like so:
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
[self.restClient uploadFile:#"ZipTest.zip" toPath:[NSString stringWithFormat:#"/%#", self.dropboxFolderName] fromPath:docsPath];
But am now trying to verify it actually completed the upload. I know I can check for errors but how to check for completion?
I have tried using:`- (void)restClient:(DBRestClient*)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath {
Buut all I get is the number 1 printed even though I see on Dropbox the file has not completed the upload yet?
any ideas?
Thanks`
- (void)restClient:(DBRestClient *)client uploadedFile:(NSString *)srcPath {
NSString *filename = [[srcPath pathComponents]lastObject];
NSString *message = [NSString stringWithFormat:#"Uploaded File:%#",filename];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success"
message:message delegate:nil cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
I used this code to check file is uploaded or not and after uploading this alert will show
in my app i am using validation keys to download content from a server using Wi-Fi. I need to show a UIAlert if the licence keys are wrong or if the wi-fi is not available. I have written the coed for displaying the alert view but the alert is not being displayed... This is scking the blood out my head... Can anyone help please....the control is going over this line, but still the alert is not being displayed.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory= [[[UIApplication sharedApplication] delegate] applicationDocumentsDirectory]; //[pathToStore objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingFormat:#"packages"];
NSString *packagePath = [NSString stringWithFormat:#"%#/%#", path,isbnTemp];
[recievedData writeToFile:[documentsDirectory stringByAppendingPathComponent:#"file.zip"] atomically:YES];
NSString *zipPath=[documentsDirectory stringByAppendingPathComponent:#"file.zip"];
[fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:NO attributes:nil error:nil];
ZipArchive *zipArchive = [[ZipArchive alloc]init];
if([zipArchive UnzipOpenFile:zipPath]){
if([zipArchive UnzipFileTo:packagePath overWrite:YES]){
[self loadContent];
}
else{
NSLog(#"Unable to UnArchieve the packages");
}
}
else {
NSLog(#"Failure To Open Archive");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Your ISBN and/or Licence Key are incorrect" message:Nil delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Are you trying to show the UIAlertView in a method that is being called from a thread other than the main thread? For example, if you are trying to show the UIAlertView in an asynchronous callback, it could be running on a separate thread.
If so, you need to move the code that shows the UIAlertView to a separate selector, and call it on the main thread using one of the performSelectorOnMainThread: methods.
For example, add the following method to your class:
-(void)showAlert {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Your ISBN and/or Licence Key are incorrect" message:Nil delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
And then change the last else clause in your current code so that it uses:
[self performSelectorOnMainThread:#selector(showAlert) withObject:nil waitUntilDone:NO];
See the NSObject class reference for more information on the performSelectorOnMainThread: methods.
After you've created the alert could you check for a NULL pointer in the alert variable?
Maybe you need to specify a message? Other than that I can't see anything wrong with the code you've posted.