我是iPhone新手,
我目前正在开发iPhone应用程序,并希望实现从互联网下载文件的功能。我创建了UIWebView
,但想知道在webview中链接文件时捕获文件的最佳方法,然后将它们下载到文档目录中的指定文件夹。
这是我的代码段,
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.fileData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
{
[self.fileData appendData:data1];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[activityIndicator stopAnimating];
activityIndicator.hidden=TRUE;
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
url = [request URL];
//CAPTURE USER LINK-CLICK.
NSString *file = [NSString stringWithString:[url absoluteString]];;
NSURL *fileURL = [NSURL URLWithString:file];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
[NSURLConnection connectionWithRequest:req delegate:self];
data = [NSData dataWithContentsOfURL:url];
//Saving file at downloaded path.
DirPath = [DestPath stringByAppendingPathComponent:[url lastPathComponent]];
[data writeToFile:DirPath atomically:YES];
UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"Download Complete !"
message:nil delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[Alert show];
[Alert release];
return YES;
}
问题是在哪里写条件,如果我的下载失败并且我在日志显示中收到警告:“wait_fences: failed to receive reply: 10004003”
答案 0 :(得分:0)
看起来你在这段代码中多次做同样的事情。例如,您创建了一个新的NSURLRequest对象,即使已经在委托方法中传递了一个对象?您还在创建新的NSURLConnection后运行同步dataWithContentsOfURL方法?您还将一些数据附加到属性中,但不对该属性执行任何操作?
您可能想要做的是在UIWebView加载时创建一个新的异步NSURLConnection。从那里,允许UIWebView加载该页面。在委托方法内部,不是将数据附加到某个属性,而是将下载的数据附加到文件中。连接完成下载后,显示警报,通知用户数据已下载并保存。