使用UI Web视图下载文件

时间:2011-03-13 15:31:47

标签: iphone objective-c ios ios4

是否可以在我的应用中下载实现UI web iphone的文件?如果是这样,文件将存储在哪里以及如何访问它?

2 个答案:

答案 0 :(得分:1)

您无法仅通过浏览文件来真正下载文件,但您可以使用

  • (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)请求navigationType:(UIWebViewNavigationType)navigationType

分析文件的链接(比如查看最后一个路径组件的扩展名),如果你想要下载这种文件,你可以使用[NSURLConnection connectionWithRequest:myURLRequest delegate:self];以及将文件下载并存储在文档文件夹中的所有相关委托方法。

答案 1 :(得分:0)

如果您想要显示一些已知的webview文件,它会自动显示...但如果页面为webview文件返回一个未知(这发生在我身上的Citrix ica文件)webview会给你一个错误.. ..解决这个问题我使用了这个代码(请注意,这里我只允许下载ica文件,但你可以改变这个条件):

-(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];

}