尝试写入普通目录时可可错误513

时间:2011-04-01 19:15:22

标签: iphone ios file-io

我只是想创建一个安全的用户文件,它将保存基本的登录信息,因此无需在每次启动应用程序时输入。我知道我不能写入bundle,所以我正在尝试我们应该访问的其他目录之一,比如高速缓存,文档和库,这些都没有导致成功写入

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, NO);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    NSLog(@"Found cache directory: %@", cacheDirectory);
    NSString *fileName = [cacheDirectory stringByAppendingPathComponent:@"987f065e4656dba6c"];
    NSString *userData = [[NSString alloc] initWithFormat:@"%@\n%@\n%@", owner.schoolWebsite.text, owner.username.text, owner.password.text];
    NSError *fileError = nil;
    if(!([[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:&fileError]))
    {
        NSLog(@"Error creating cache directory: %@\n%@\n%@\n%@", [fileError localizedDescription], [fileError localizedFailureReason], [fileError localizedRecoveryOptions], [fileError localizedRecoverySuggestion]);
    }        
    if (!([[NSFileManager defaultManager] createFileAtPath:fileName contents:[userData dataUsingEncoding:NSASCIIStringEncoding] attributes:nil] ) )

    {
        NSLog(@"ERROR WRITING TO FILE: %@\n%@\n%@\n%@", [fileError localizedDescription], [fileError localizedFailureReason], [fileError localizedRecoveryOptions], [fileError localizedRecoverySuggestion]);
    }

这一直困扰着我一段时间,而这只会在设备上失败

1 个答案:

答案 0 :(得分:2)

尝试替换它:

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

机智:

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

我已将NSLibraryDirectory(/ Library)替换为NSCachesDirectory(/ Library / Cache)。也表示将波浪扩展到完整路径,这可能是这背后的主要原因。