Reputation: 4039
I'm trying to download and cache data in iPhone document directory. I would like to be able to check to see if a file exists and populate my UITableViewCell with the local data if it exists, and load the data remotely if it does not.
Here is the code I am using to download the data.
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);
}];
Upvotes: 0
Views: 658
Reputation: 1214
You want the documents directory right? Use this code:
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
}
Note: You might want to check if AFNetworking creates a directory in the document path for storing anything it downloads. These libraries usually create their own directories.
Upvotes: 0
Reputation: 124997
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathToMyFile = [path stringByAppendingPathComponent:@"myDataFile"];
if ([fileManager fileExistsAtPath:pathToMyFile]) {
// file exists
}
else {
// file doesn't exist
}
Upvotes: 2