Access files in “private Documents” folder transfe

2020-07-27 03:03发布

问题:

Currently I'm trying to access the files that are transferred using the new iOS feature introduced with 3.2.

- (NSString *)getPrivateDocsDir {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    documentsDirectory = [documentsDirectory stringByAppendingPathComponent:@"Private Documents"];

    NSError *error;
    [[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:&error];   

    return documentsDirectory;

}


 // and then in a method
 NSString *documentsDirectory = [self getPrivateDocsDir];
 NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];

The problem is, this works fine in simulator, but on my iphone, the files array is empty.

Any ideas how to access this directory directly?

回答1:

The Library-Directory is not accessible through iTunes, and "Private Documents" is inside this library directory. The private documents, are, as the name suggests, private. They are intentionally not accessible through iTunes.

If you want to access the documents directory (which is accessible through itunes) replace this

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

with this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

EDIT: Access the files like this.

- (NSString *)documentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

NSString *documentsDirectory = [self documentsDirectory];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];