我是iPhone新手,
我目前正在开发一款iPhone应用,并希望实现从网址下载文件的功能。我创建了UIWebView
,当我点击webview下载中的download
链接时,我会将该文件保存到文档目录中的指定文件夹中。但我无法看到我下载的文件。
这是我的代码段,
//CAPTURE USER LINK-CLICK in UIwebView.
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:DUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
receivedData = [[NSMutableData data] retain];
} else {
NSLog(@"Inform the user that the connection failed.");
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
{
[receivedData appendData:data1];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
DirPath=[self MyApplicationDocumentDirectory];
[receivedData writeToFile:DirPath atomically:YES];
UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"Download Complete !"
message:nil delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[Alert show];
[Alert release];
// release the connection, and the data object
[connection release];
[receivedData release];
}
任何帮助都会得到满足。
修改
BOOL success =[[NSFileManager defaultManager] fileExistsAtPath:MyDirPath];
if (success)
{
UIAlertView* innerAlert = [[UIAlertView alloc] initWithTitle:@"Already downloaded."
message:@"Do you want to Downlaod again ?" delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"Yes",@"No",nil];
[innerAlert show];
[innerAlert release];
}
在哪里写这个条件?
答案 0 :(得分:2)
编辑在写入(保存)下载数据之前,检查下载的文件是否已经在doc dir中退出:
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:DirPath error:nil];
BOOL fileExists = NO;
for(NSString *fileName in dirContents)
{
NSString *filePath = [DirPath stringByAppendingPathComponent:fileName];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
if([receivedData isEqualToData:fileData]) //your receivedData here
{
fileExists = YES;
}
}
if(fileExists)
{
NSLog(@"File exists");
}
else
{
NSLog(@"File does not exists");
}
你忘了提供fileName来写数据:
DirPath=[self MyApplicationDocumentDirectory];
NSString *filePath = [DirPath stringByAppendingPathComponent:@"yourFileName"];
[receivedData writeToFile:filePath atomically:YES];