AFNetworking下载后的文件存在
问题描述:
我下载后与AFNetworking下载后发现我的文件存在一些问题... 下载本身没问题,但是当我检查文件的存在后,我找不到它...所以我希望有人能帮助我...AFNetworking下载后的文件存在
在我的代码中,我下载文件,并在完成块,我检查存在(这是因为我之后会被删除)...
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"url to file removed"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"filename removed"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:@"filename removed" append:NO];
//Track the progress
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
if (totalBytesExpectedToRead > 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSString *progress = [NSString stringWithFormat:@"Downloaded %lld of %lld bytes",
totalBytesRead,
totalBytesExpectedToRead];
NSLog(@"%@", progress);
});
}
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"File downloaded to %@", path);
//Check for existence
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath:path])
{
NSLog(@"File found");
} else
{
NSLog(@"File not found");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error: %@", error);
}];
[operation start];
任何想法可能会出错吗?由于下载本身没问题,所以问题必须在于将文件/文件系统保存在iOS中...
答
您尝试写入的目录是否存在?如果不是,您可能会发现[NSOutputStream outputStreamToFileAtPath:@"filename removed" append:NO]
正在返回nil
。
先尝试创建目录:
NSFileManager *fm = [NSFileManager defaultManager];
NSString *folder = [@"filename removed" stringByDeletingLastPathComponent];
if (![fm fileExistsAtPath:folder]) {
[fm createDirectoryAtPath:folder
withIntermediateDirectories:YES
attributes:nil
error:nil];
}
我希望帮助。