简体   繁体   English

iOS-在文档中创建目录

[英]iOS-Creating a directory in Documents

I'm trying to create a folder in my documents directory and I want to be able to do it without typing out /Users/(username)/Documents/Foo/Bar 我正在尝试在我的文档目录中创建一个文件夹,并且希望能够在不输入/ Users /(用户名)/ Documents / Foo / Bar的情况下进行操作

NSString *directoryPath = [NSString stringWithFormat:@"%@/Documents/Foo/Bar", NSHomeDirectory()];    

BOOL isDir;
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:directoryPath isDirectory:&isDir])
    if(![fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:NULL])
        NSLog(@"Error: Create folder failed %@", directoryPath);

This doesn't work when I try using NSHomeDirectory() with it. 当我尝试将其与NSHomeDirectory()一起使用时,此方法不起作用。 But if I typed out the full path /Users/(username)/Documents/Foo/Ba it works. 但是,如果我输入完整的路径/ Users /(用户名)/ Documents / Foo / Ba则可以。 How can it be done to not have to know the users folder? 不必知道用户文件夹怎么办?

EDIT: directoryPath becomes 编辑:directoryPath变为

/Users/(username)/Library/Developer/CoreSimulator/Devices/FAB78255-38D2-49BE-9683-7A0676EA2288/data/Containers/Data/Application/67B0AACE-572A-4808-9535-D221AEEB9EFA/Foo/Bar

I just want /Users/(username) 我只想要/ Users /(用户名)

This is an iOS app. 这是一个iOS应用。 The "Documents" folder of an iOS app's sandbox is not at all related to the user's "Documents" folder on their computer. iOS应用的沙箱中的“文档”文件夹与用户计算机上的“文档”文件夹根本不相关。

Since you appear to be running your iOS in the simulator, the path you are getting is more like what you should be seeing. 由于您似乎正在模拟器中运行iOS,因此获得的路径更像您应该看到的样子。 You do not want a path in the user's home directory. 希望在用户的主目录的路径。

Keep in mind that you can't get access to the "Documents" folder of an iOS app using NSHomeDirectory() . 请记住,您无法使用NSHomeDirectory()访问iOS应用的“ Documents”文件夹。 That may have worked in older versions of iOS but it fails in iOS 8 and later. 这可能在旧版本的iOS中有效,但在iOS 8及更高版本中失败。 The proper code needs to be something like this: 正确的代码必须是这样的:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = paths[0];
NSString *directoryPath = [documentsFolder stringByAppendingPathComponent:@"Foo/Bar"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM