尝试从XML Feed下载多个文件。有几个类别,每个类别都有未知数量的图像。我为每个类别创建一个子目录,没问题。当我尝试将每个文件下载到相应的类别时,每个文件都会为Feed中的每个图像写入相同的数据。
-(void)parsingComplete:(XMLDataSource*)theParser
{
/* iterate through the Categories and create the
sub-directory if it does not exist
*/
for (int i = 0; i < [categories count]; i++)
{
NSString *cat = [NSString stringWithFormat:@"%@/%@",BASE_DIR,[[categories objectAtIndex:i] objectForKey:@"name"]];
NSString *catName = [[categories objectAtIndex:i] objectForKey:@"name"];
NSArray *catArray = [[categories objectAtIndex:i] objectForKey:@"images"];
/* create the sub-direcotry naming it the #category# key */
if (![FILEMANAGER fileExistsAtPath:cat]) {
[FILEMANAGER createDirectoryAtPath:cat withIntermediateDirectories:NO attributes:nil error:nil];
}
//NSLog(@"\n\nCategory: %@",cat);
for (int x = 0; x < [catArray count]; x++)
{
/* download each file to the corresponding category sub-directory */
fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];
NSURLRequest * imageRequest =
[NSURLRequest requestWithURL:[NSURL URLWithString:[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
[[NSURLConnection alloc] initWithRequest:imageRequest delegate:self];
}
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[receivedData writeToFile:fileOut atomically:YES];
}
答案 0 :(得分:3)
是的,这就是我提到的in my comment。每次调用connectionDidFinishLoading:
时,您都会得到一个连接的结果。如果循环遍历所有文件名,则会反复将相同的数据块写入所有这些名称。每次通过parsingComplete:
中的for循环,您都会创建一个新连接,获取一个新的数据对象,然后多次写出同一个对象。在parsing...
循环结束后,您将获得一个包含上次连接数据的文件列表。
我很累,我不确定:我是否清楚?
发表评论:
您可能必须为委托方法提供当前连接的正确文件名,可能是将其放在ivar中,或者转到同步路由。将它放在像currFileName
这样的ivar中,这样这个类中的所有方法都可以访问它,这可能是完成工作的最简单的方法。
/* In parsingCompleted: */
for (int x = 0; x < [catArray count]; x++)
{
/* download each file to the corresponding category sub-directory */
// fileOut is an instance variable
fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];
imageRequest = [NSURLRequest etc...
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// No loop; just use that file name that you set up earlier;
// it correctly corresponds to the current NSURLConnection
[receivedData writeToFile:fileOut atomically:YES];