如何在 Swift 中找到正确的路径

How to find a correct path in Swift

我从文档中得到这段代码,我找不到我的文件的路径,我需要将 "contacts.db" 文件从支持文件文件夹复制到设备中的应用程序,而不是在模拟器中离线使用。

func copyItemAtPath(_ srcPath: String,
         toPath dstPath: String,
          error error: NSErrorPointer) -> Bool

srcPath = 您要移动的文件或目录的路径。此参数不能为零。

dstPath = 放置 srcPath 副本的路径。此路径必须包括文件或目录在其新位置的名称。此参数不能为零。

error = 在输入时,指向错误对象的指针。如果发生错误,此指针将设置为包含错误信息的实际错误对象。如果您不想要错误信息,您可以为此参数指定 nil。

非常感谢任何帮助。 :)

您只需将 "contacts.db" 拖放到项目导航器中,然后您就可以通过以下方式找到该文件的路径:

let sourcePath = NSBundle.mainBundle().pathForResource("contacts", ofType: "db")

之后,您可以将该文件复制到应用程序的文档文件夹中,为此您需要该文档文件夹路径:

let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let destinationPath = doumentDirectoryPath.stringByAppendingPathComponent("contacts1.db")

现在您有 sourcePathdestinationPath,因此您可以将该文件复制到文档文件夹中:

NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)

如果你想检查错误,你可以这样做:

var error : NSError?
    NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)
    if let error = error {
        println(error.description)
    }

如果您得到的是 sourcePath nil,则转到 Targets->YouApp->Build Phases->copy Bundle Resources 并在其中添加您的文件。 希望这会有所帮助。