0

我正在尝试在 iPhone 文档目录中下载和缓存数据。我希望能够检查文件是否存在,如果存在则用本地数据填充我的 UITableViewCell,如果不存在则远程加载数据。

这是我用来下载数据的代码。

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"The Error Is: %@", error);
    }];
4

2 回答 2

2
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathToMyFile = [path stringByAppendingPathComponent:@"myDataFile"];
if ([fileManager fileExistsAtPath:pathToMyFile]) {
    // file exists
}
else {
    // file doesn't exist
}
于 2013-02-14T21:51:31.027 回答
0

您想要文档目录吗?使用此代码:

NSString* documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"FILENAME"];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    // file exists
}
else {
    // file doesn't exist
}

注意:您可能需要检查 AFNetworking 是否在文档路径中创建了一个目录来存储它下载的任何内容。这些库通常会创建自己的目录。

于 2013-02-19T16:09:33.470 回答