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 に答える