【发布时间】:2015-06-14 08:40:53
【问题描述】:
我正在使用 Swift OS X 10.10 应用程序自学 Apple 开发。我想将文件 URL 传递给 NSXMLParser。该文件很大,并且与我的应用程序位于单独的磁盘上。我创建了 NSURL,但是当我使用 checkPromisedItemIsReachableAndReturnError() 检查它时,我总是得到一个“没有这样的文件或目录错误”。
看起来当我在 Xcode 中运行我的应用程序时,有些东西将应用程序的开发目录添加到我的文件路径中,所以"/Volumes/bigdrive/data.xml" 变成了"/Users/charlweed/Library/Developer/Xcode/DerivedData/dataskunk-ghkiumvdkopxarhavynetidlqxio/Build/Products/Debug/file:/Volumes/bigdrive/data.xml"
我在创建项目时没有启用沙盒或 iCloud。我想我可能需要使用 NSURL.startAccessingSecurityScopedResource() ,但它总是返回 true。我究竟做错了什么?这是Swift中的一个测试函数,我不知道objective-c,但我希望我能找到objective-c的答案:
func accessFile() {
/**I belive this URI is correct, becuase everything after the file:// works in the OS X bash*/
let xmlInFilePath = "file:///Volumes/Seagate_1tib/projects/dataskunk/wasteproduct.xml"
if let xmlInFileURL = NSURL.fileURLWithPath(xmlInFilePath)
{
println("Unwrapped \(xmlInFileURL)")
var securityURLBS = xmlInFileURL.startAccessingSecurityScopedResource()
if securityURLBS
{
var xmlFileError: NSError?
if xmlInFileURL.checkPromisedItemIsReachableAndReturnError(&xmlFileError)
{
println("Can access file. huray!")
/** Use the file URL**/
}
else
{
/** This Always happens with a "No such file or directory " :( **/
println("\(xmlFileError)")
}
}
else
{
println("Could not get Security Scoped Resource")
}
xmlInFileURL.stopAccessingSecurityScopedResource()
}
else
{
log(" NSURL.fileURLWithPath() returned nil for \(xmlInFilePath)")
}
}
这是错误的转储:
解包文件:/Volumes/Seagate_1tib/projects/dataskunk/apple_rss.xml -- file:///Users/charlweed/Library/Developer/Xcode/DerivedData/Keepass2Keyring-ghkiumvdkopxarhavynetidlqxio/Build/Products/Debug/
Optional(Error Domain=NSCocoaErrorDomain Code=260 "无法打开文件“wasteproduct.xml”,因为没有这样的文件。"
UserInfo=0x61000006f9c0 NSURL=file:/Volumes/Seagate_1tib/projects/dataskunk/wasteproduct.xml -- file:///Users/charlweed/Library/Developer/Xcode/DerivedData/Keepass2Keyring-ghkiumvdkopxarhavynetidlqxio/Build/Products/Debug /,
NSFilePath=/Users/charlweed/Library/Developer/Xcode/DerivedData/Keepass2Keyring-ghkiumvdkopxarhavynetidlqxio/Build/Products/Debug/file:/Volumes/Seagate_1tib/projects/dataskunk/wasteproduct.xml,
NSUnderlyingError=0x610000044a10 "操作无法完成。没有这样的文件或目录"})
【问题讨论】:
-
只是为了让您知道字符串是否具有前缀 file:// 您需要使用 NSURL 方法 filePathForURL() 创建一个 url 然后您可以使用路径扩展名从该 NSURL 中提取路径
-
你的具体意思是什么? NSURL 类上没有“filePathForURL”方法。至少目前没有它的文档,当我尝试引用它时编译器抱怨它不存在。
-
对不起,它被称为 fileURLWithPath
标签: xcode swift file-io osx-yosemite