1

使用 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中保存文件/文件系统......

4

1 回答 1

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];
}

我希望这会有所帮助。

于 2013-03-04T15:37:32.440 回答