use*_*268 3 nsfilemanager ios swift
我试着调用fileManager.createFileAtPath-method,但总是失败.我的变量success总是如此false.我在这里查看了一些类似的帖子,但完全不符合我的需求.这是我的代码:
pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)
let data: NSData = NSData()
var isDir: ObjCBool = false
if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)
{
print("File already exists")
}
else
{
let success = fileManager.createFileAtPath(String(pListPath), contents: data, attributes: nil)
print("Was file created?: \(success)")
print("plistPath: \(pListPath)")
}
Run Code Online (Sandbox Code Playgroud)
这是我试图解决这个问题的方法:
我试着用这个方法
let success = NSFileManager.defaultManager().createFileAtPath(String(pListPath), contents: data, attributes: nil)
Run Code Online (Sandbox Code Playgroud)
并且
let success = data.writeToFile(String(pListPath), atomically: true)
Run Code Online (Sandbox Code Playgroud)
但没有任何作用.success永远false.我也尝试给它一个文字字符串作为路径,设置contents为nil,我甚至改变了目录权限,我想把它放到777,但注意到工作.success总是假的.我希望你能帮我解决这个问题.任何帮助都非常感谢.谢谢
Mar*_*n R 10
这是一个问题:
if fileManager.fileExistsAtPath(String(pListPath), isDirectory: &isDir)
Run Code Online (Sandbox Code Playgroud)
您不能使用String(...)将a转换NSURL为文件路径字符串,您必须使用以下path方法:
if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)
Run Code Online (Sandbox Code Playgroud)
如果reportsPath也是,NSURL则存在同样的问题
pListPath = NSURL(fileURLWithPath: String(reportsPath)).URLByAppendingPathComponent("myReports.plist", isDirectory: false)
Run Code Online (Sandbox Code Playgroud)
应该是
let pListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)
Run Code Online (Sandbox Code Playgroud)
确保您尝试在已存在的文件夹中创建文件。首先创建文件夹,然后您可以在该路径创建文件。
private class func assureDirPathExists(path: String)
{
if !NSFileManager.defaultManager().fileExistsAtPath(path)
{
do {
try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
Run Code Online (Sandbox Code Playgroud)
确保您正在相对于用户域文件夹写入文件。
// i.e. Caches, Documents...
let rootPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
Run Code Online (Sandbox Code Playgroud)
可能,您缺少斜杠字符,或者您先跳过了某些文件夹的创建。
如果你有 ...dir1/dir2/file.ext,那么你需要创建 dir1,然后是 dir2,最后是 file.ext。
| 归档时间: |
|
| 查看次数: |
5687 次 |
| 最近记录: |