IOS限制在沙箱中写入文件

时间:2013-12-23 22:51:25

标签: ios sandbox

我正在尝试在我的应用沙箱中的/Documents/Library文件夹之间移动一些文件,但我遇到了每个复制操作都失败的问题。

来自Objective-c书的这个简单代码在非IOS相关项目中完美运行:

    NSString          *dirName = @"testdir";
    NSString          *path;
    NSFileManager     *fm;            
    // Need to create an instance of the file manager            
    fm = [NSFileManager defaultManager];
    // Get current directory
    path = [fm currentDirectoryPath];
    NSLog (@"Current directory path is %@", path);
    // Create a new directory
    if ([fm createDirectoryAtPath: dirName withIntermediateDirectories: YES
                       attributes: nil error: NULL] == NO) {
        NSLog (@"Couldn't create directory!");
        return 1;
    }            
    // Rename the new directory           
    if ([fm moveItemAtPath: dirName toPath: @"newdir" error: NULL] == NO) {
        NSLog (@"Directory rename failed!");
        return 2;
    }            
    // Change directory into the new directory
    if ([fm changeCurrentDirectoryPath: @"newdir"] == NO) {
        NSLog (@"Change directory failed!");
        return 3;
    }           
    // Now get and display current working directory
    path = [fm currentDirectoryPath];
    NSLog (@"Current directory path is %@", path);
    NSLog (@"All operations were successful!");
}        return UIApplicationMain(argc, argv, nil, NSStringFromClass([writingAppDelegate class]));

...但在嵌入到IOS应用程序时无效,返回错误:

2013-12-23 14:37:32.781 writingTest[30972:70b] Couldn't create directory!

不确定我是否遗漏了Iphone应用沙盒中允许的文件操作的任何众所周知的限制,但我将非常感谢您的帮助。

谢谢,      DOM

1 个答案:

答案 0 :(得分:0)

问题是你没有提供创建directoryAtPath的完整路径,所以当执行到达这一点时:

if ([fm createDirectoryAtPath: dirName withIntermediateDirectories: YES
                       attributes: nil error: NULL] == NO) {

dirname包含“testdir”,而不是完整路径。

您要做的是获取Documents目录:

- (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

然后附加您要创建的目录名称:

if ([fm createDirectoryAtPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent:dir] withIntermediateDirectories: YES
                           attributes: nil error: NULL] == NO) {

检查File System Programming Guide