Objective c 检查应用程序作用域书签下的路径是否可在沙盒应用程序中写入

Objective c 检查应用程序作用域书签下的路径是否可在沙盒应用程序中写入,objective-c,swift,security,sandbox,appstore-sandbox,Objective C,Swift,Security,Sandbox,Appstore Sandbox,我有一个OSX应用程序,它存储一个应用程序范围的书签,以持久访问某些目录。我可以毫无问题地写入这些目录,但是在我的代码中有一部分我想做额外的检查,以确认路径是可写的,并且它失败了 var fileManager: NSFileManager = NSFileManager.defaultManager() var baseUrl: NSURL = try! NSURL(byResolvingBookmarkData: data, …) var fileUrl: NSURL = url.URLBy

我有一个OSX应用程序,它存储一个应用程序范围的书签,以持久访问某些目录。我可以毫无问题地写入这些目录,但是在我的代码中有一部分我想做额外的检查,以确认路径是可写的,并且它失败了

var fileManager: NSFileManager = NSFileManager.defaultManager()
var baseUrl: NSURL = try! NSURL(byResolvingBookmarkData: data, …)
var fileUrl: NSURL = url.URLByAppendingPathComponent("foo.txt")

// Changing this order has no effect, I make only the first start access call,
// the second one is to demonstrate that it's not working.

baseUrl.startAccessingSecurityScopedResource() // true
fileUrl.startAccessingSecurityScopedResource() // false

// File manager confirms that base path is writable, but anything inside
// it – not. This worked perfectly fine before sandboxing the app.

fileManager.isWritableFileAtPath(baseUrl.path!) // true
fileManager.isWritableFileAtPath(fileUrl.path!) // false

// Writing file to the `fileUrl` works anyway, even though
// file manager thinks it's not writable.

writeMyFile(toUrl: fileUrl)

// Here's another interesting observation, is writable starts working
// once the files get created.

fileManager.isWritableFileAtPath(fileUrl.path!) // false
fileManager.createFileAtPath(fileUrl.path!, contents: nil, attributes: nil)
fileManager.isWritableFileAtPath(fileUrl.path!) // true

我是做错了什么,还是沙箱中的文件管理器有问题?是否有一种合适的方法来检查子路径是否可写,即不创建文件?

在我看来,这和预期的一样。只要文件不存在,就没有可读取和写入的内容,因此不会授予访问权限。你试过使用NSURLKeys吗?NSURLIsReadableKey in NSURL-(BOOL)getResourceValue:(out id*)value forKey:(NSString*)keyStarting访问它并不是一个问题,我只是想说明使用它并没有什么区别。关键是
isWritableFileAtPath
返回
false
,而path实际上是可写的。“无文件=无可写”有一定道理,但在非沙盒环境中,它可以很好地处理不存在的文件,而且我已经学会了期望它实际上能像这样工作。在后台检查目录是否可写,并返回沙盒中不存在的文件的
true
,这似乎是一个不错的解决方案。相反,现在看来每次都必须手工完成。@IanBytchek-找到解决方案了吗?我遇到了完全相同的问题。@kev不,不走运……我已经在墙上撞了几天,测试了我能找到的所有东西,并放弃了使用
try catch
和其他必要的检查。沙盒附带了一些f-up案例,我使用
-DSANDBOX
编译器标志以不同方式处理一些此类案例。除此之外,我没有别的建议。如果你不辞辛劳地找到了解决方案,请分享!:)@IanBytchek如果您只在文件不可读的情况下才开始访问该文件,这对您有帮助吗<代码>如果let path=url?.path其中NSFileManager.defaultManager().isReadableFileAtPath(path)==false{url?.startAccessingSecurityScopedResource();}