AFNetworking下载后文件存在

时间:2012-11-22 11:47:04

标签: afnetworking nsfilemanager

我在使用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中的文件/文件系统......

1 个答案:

答案 0 :(得分:5)

您尝试写入的目录是否存在?如果不是,您可能会发现[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];
}

我希望有所帮助。