web-dev-qa-db-ja.com

Swift code(NSFileManager)を使用してディレクトリを作成する方法

Objective-Cコードを変換してSwift用のディレクトリを作成するのに問題があります。

Objective-C:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
42
Gian

Swift 5.

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let docURL = URL(string: documentsDirectory)!
let dataPath = docURL.appendingPathComponent("MyFolder")
if !FileManager.default.fileExists(atPath: dataPath.absoluteString) {
    do {
        try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
    } catch {
        print(error.localizedDescription);
    }
}

Swift 4.

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0] as AnyObject
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!

do {
    try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription);
}

Swift 3.

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")!

do {
    try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription);
}

Swift 2.1

以下の方法を使用してディレクトリを作成できます。

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
let dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")

do {
    try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
    print(error.localizedDescription);
}
92
Kampai

@Kampaiと@Crashalotの答えはどれも役に立たなかった。

。absoluteStringは、file://プレフィックスを持つURLを作成し、ディレクトリの作成中に例外を発生させます。代わりに。pathメソッドを使用しました。

Swiftの固定コード

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dataPath = documentsDirectory.appendingPathComponent("MyFolder")

do {
    try FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
    print("Error creating directory: \(error.localizedDescription)")
}
60

appendingPathComponentを含む行がエラーを生成するため、受け入れられた回答はコンパイルされなくなりました。

コンパイルするSwift 3バージョン:

fileprivate func createDir(dirName: String) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let dataPath = documentsDirectory.appendingPathComponent(dirName)

    do {
        try FileManager.default.createDirectory(atPath: dataPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
    } catch let error as NSError {
        printError("Error creating directory: \(error.localizedDescription)")
    }
}
5
Crashalot

Swift 4:

NSSearchPathForDirectoriesInDomainsは、URLではなく、文字列の配列を返します。

文字列にappendingPathComponentを指定すると、アプリでクラッシュします-[NSPathStore2 URLByAppendingPathComponent:]:認識されないセレクターがインスタンスに送信されました

コンパイルするSwift 4バージョンです:

    let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    if let pathURL = URL.init(string: paths[0]) {
        let dataURL = pathURL.appendingPathComponent("MyFolder")
        do {
            try FileManager.default.createDirectory(atPath: dataURL.absoluteString, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            print(error.localizedDescription);
        }
    }
    else {
        print("Error in getting path URL");
    }
3
Dhasdhageerkhan

スイフト4

// DB Directory and Path
lazy var applicationDocumentsDirectory: URL = {

    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentDirectoryURL = urls[urls.count - 1] as URL
    let dbDirectoryURL = documentDirectoryURL.appendingPathComponent("DB")

    if FileManager.default.fileExists(atPath: dbDirectoryURL.path) == false{
        do{
            try FileManager.default.createDirectory(at: dbDirectoryURL, withIntermediateDirectories: false, attributes: nil)
        }catch{
        }
    }
    return dbDirectoryURL
}()
1
GSK

より簡単なソリューション:

"~/Desktop/demo".expand.createDir()//Now you have a folder named demo on your desk

extension String{
    func createDir(_ path:String){
        do {
            try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }
    }
    var expand:String {return NSString(string: self).expandingTildeInPath}
}
0
eonist

他の開発者の場合、フォルダの作成場所を把握する方法を探している私のような人に役立つかもしれないので、ここに残しておきます。

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDir = paths.firstObject as String
println("Path to the Documents directory\n\(documentsDir)")
0
bona912