无法从 Swift 中的包复制文档目录中的文本
Not able to copy text in documents Directory from bundle in Swift
我是 iOS 开发新手。我在我的应用程序包中添加了一个文件 "name.txt",我正在尝试将其复制到文档目录。但我不知道我在哪里犯了错误。该文件未显示在文档目录中。我包括 code.Can 有人帮忙吗?
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)
}
}
}
关于 toPath
copyItemAtPath() 的文档说:
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.
因此您需要确定并将文件名附加到 docsDir
:
let destPath = (docsDir as NSString).stringByAppendingPathComponent("/name.txt")
或类似的东西。
我是 iOS 开发新手。我在我的应用程序包中添加了一个文件 "name.txt",我正在尝试将其复制到文档目录。但我不知道我在哪里犯了错误。该文件未显示在文档目录中。我包括 code.Can 有人帮忙吗?
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)
}
}
}
关于 toPath
copyItemAtPath() 的文档说:
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.
因此您需要确定并将文件名附加到 docsDir
:
let destPath = (docsDir as NSString).stringByAppendingPathComponent("/name.txt")
或类似的东西。