简体   繁体   English

无法从Swift中的捆绑软件复制文档目录中的文本

[英]Not able to copy text in documents Directory from bundle in Swift

I am new to iOS Development. 我是iOS开发的新手。 I have added a file "name.txt" in my app bundle and I am trying to copy it to the Documents Directory. 我在应用程序捆绑包中添加了文件“ name.txt”,并且尝试将其复制到文档目录。 But I don't know where I am making mistake. 但是我不知道我在哪里犯错。 The file is not showing in the document Directory. 该文件未显示在文档目录中。 I am including the code.Can anybody help ? 我包含了代码。有人可以帮忙吗?

  func copyFile()
  {
  let dirPaths =  NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
    let docsDir = dirPaths[0] as String
    var error:NSError?

    var fileMgr = NSFileManager.defaultManager()

    if let path = NSBundle.mainBundle().pathForResource("name", ofType:"txt") {
        println(path)
        if fileMgr.copyItemAtPath(path, toPath: docsDir, error: &error) == true{
            println("success")
        }
        else{
            println("failed")
            println(error?.localizedDescription)
        }
    }

    if let files = fileMgr.contentsOfDirectoryAtPath(docsDir, error: &error)
    {
        for filename in files{
            println(filename)
        }
    }
}

Concerning toPath the documentation for copyItemAtPath() says: 关于toPathcopyItemAtPath()的文档说:

The path at which to place the copy of srcPath. 放置srcPath副本的路径。 This path must include the name of the file or directory in its new location. 该路径必须在新位置包含文件或目录的名称。 This parameter must not be nil. 此参数不能为nil。

So you need to be sure and append the filename to docsDir : 因此,您需要确定并将文件名附加到docsDir

let destPath = (docsDir as NSString).stringByAppendingPathComponent("/name.txt")

or something similar. 或类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM