Create Directory in Swift 3.0

2020-01-30 08:13发布

I am a new student in 9th grade learning swift, creating a school project .

I am trying to create a directory where I want to save a scanned file into pdf format.

While creating directory I am getting error below.

Error 1:

Cannot use instance member 'filemgr' within property initializer; property initializers run before 'self' is available.

Error 2:

Expected declaration

Code:

let filemgr = FileManager.default


let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)

let docsURL = dirPaths[0]

let newDir = docsURL.appendingPathComponent("data").path

do{
    try filemgr.createDirectory(atPath: newDir,withIntermediateDirectories: true, attributes: nil)
} catch {
    print("Error: \(error.localizedDescription)")
}

Please assist me in resolving this issue.

Thanks.

标签: ios swift swift3
4条回答
劫难
2楼-- · 2020-01-30 08:54

For Swift 4.0, I created the following extension off of URL that allows for the creation of a folder off of the documents directory within the application.

import Foundation

extension URL {
    static func createFolder(folderName: String) -> URL? {
        let fileManager = FileManager.default
        // Get document directory for device, this should succeed
        if let documentDirectory = fileManager.urls(for: .documentDirectory,
                                                    in: .userDomainMask).first {
            // Construct a URL with desired folder name
            let folderURL = documentDirectory.appendingPathComponent(folderName)
            // If folder URL does not exist, create it
            if !fileManager.fileExists(atPath: folderURL.path) {
                do {
                    // Attempt to create folder
                    try fileManager.createDirectory(atPath: folderURL.path,
                                                    withIntermediateDirectories: true,
                                                    attributes: nil)
                } catch {
                    // Creation failed. Print error & return nil
                    print(error.localizedDescription)
                    return nil
                }
            }
            // Folder either exists, or was created. Return URL
            return folderURL
        }
        // Will only be called if document directory not found
        return nil
    }
}

If the desired folder does not exist, it will create it. Then, assuming the folder exists, it returns the URL back to the user. Otherwise, if it fails, then nil is returned.

For example, to create the folder "MyStuff", you would call it like this:

let myStuffURL = URL.createFolder(folderName: "MyStuff")

This would return:

file:///var/mobile/Containers/Data/Application/4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24/Documents/MyStuff/

You can also create nested folders with the following:

let myStuffHereURL = URL.createFolder(folderName: "My/Stuff/Here")

Which gives you:

file:///var/mobile/Containers/Data/Application/4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24/Documents/My/Stuff/Here/

查看更多
我想做一个坏孩纸
3楼-- · 2020-01-30 08:55

For Swift 4.0 Please use this

    let fileManager = FileManager.default
    if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
        let filePath =  tDocumentDirectory.appendingPathComponent("\(FOLDER_NAME)") 
        if !fileManager.fileExists(atPath: filePath.path) {
            do {
                try fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                NSLog("Couldn't create document directory")
            }
        }
        NSLog("Document directory is \(filePath)")
    }
查看更多
虎瘦雄心在
4楼-- · 2020-01-30 09:06

You are getting this because you are assigning value to newDir instance at wrong place.

I wrote your code in viewDidLoad and it works perfectly.

enter image description here

查看更多
贪生不怕死
5楼-- · 2020-01-30 09:17

Pls, use this code:

Swift 4.0 And Swift 3.0

let DocumentDirectory = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let DirPath = DocumentDirectory.appendingPathComponent("FOLDER_NAME")
do
{
    try FileManager.default.createDirectory(atPath: DirPath!.path, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
    print("Unable to create directory \(error.debugDescription)")
}
print(DirPath!)
查看更多
登录 后发表回答