How to create directory using Swift code (NSFileManager)

前端 未结 8 2060
一个人的身影
一个人的身影 2020-12-23 12:49

I\'m having some trouble with converting Objective-C code to create a directory for Swift.

Objective-C:

    NSArray *paths = NSSearchPathForDirectori         


        
相关标签:
8条回答
  • 2020-12-23 13:19

    None of @Kampai and @Crashalot's answers worked for me.

    The .absoluteString makes a url with file:// prefix and it cause exception while creating directory. Instead I've used .path method.

    The fixed code for Swift 3

    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)")
    }
    
    0 讨论(0)
  • 2020-12-23 13:19

    Swift 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
    }()
    
    0 讨论(0)
提交回复
热议问题