简体   繁体   中英

Not able to copy text in documents Directory from bundle in Swift

I am new to iOS Development. I have added a file "name.txt" in my app bundle and I am trying to copy it to the Documents Directory. 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:

The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil.

So you need to be sure and append the filename to docsDir :

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

or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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