我是swift的新手,我不确定如何从字符串路径(或某种File/ NSFile
对象)制作新文件夹
这是在OS X上使用Cocoa。
答案 0 :(得分:9)
我的理解是你正在尝试使用swift以编程方式创建目录。下面给出的代码也是如此。
var err: NSErrorPointer = nil
let manager = NSFileManager.defaultManager()
manager.createDirectoryAtPath("/Users/abc/Desktop/swiftDir", withIntermediateDirectories: true, attributes: nil, error: err)
答案 1 :(得分:6)
Xcode 8•Swift 3
extension FileManager.SearchPathDirectory {
func createSubFolder(named: String, withIntermediateDirectories: Bool = false) -> Bool {
guard let url = FileManager.default.urls(for: self, in: .userDomainMask).first else { return false }
do {
try FileManager.default.createDirectory(at: url.appendingPathComponent(named), withIntermediateDirectories: withIntermediateDirectories, attributes: nil)
return true
} catch {
print(error)
return false
}
}
}
用法:
if FileManager.SearchPathDirectory.desktopDirectory.createSubFolder(named: "untitled folder") {
print("folder successfully created")
}
答案 2 :(得分:4)
在Swift 2.0中,您必须使用新样式进行错误处理:
let path: String = "/Users/abc/Desktop/swiftDir"
let fileManager = NSFileManager.defaultManager()
do
{
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
print("Error while creating a folder.")
}