5
有沒有辦法從UIWebView
我使用此代碼對我IBAction
事件下載文件從iPhone SDK的UIWebView中下載文件
- (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
}
} 這段代碼UIWebView
打開文件,我想下載當我按下按鈕打開的文件得到保存。 但我想我的UIWebView
表現得像普通瀏覽器,當下載鏈接出現在它和用戶按下它,UIWebView
顯示對話框選項打開它或保存它,如果用戶按保存該文件自動獲取保存,如果用戶按下打開它的文件應該在UIWebView
中打開。
謝謝塞爾吉奧的回答併爲您的迴應你的評論行指導我很多:) –
@Sergio如果我嘗試下載一個文件(可能來自雅虎/交易所服務器)它將有計劃爲**大膽** https **大膽**和pathExtension是例如一些隨機字符串。 ashx等...!我如何提示下載這些文件!對此有何想法? – Nirav