在Swift 3.0中创建目录

时间:2021-09-07 16:24:02

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

我是一名快速学习9年级的新生,创建了一个学校项目。

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

我正在尝试创建一个目录,我想将扫描文件保存为pdf格式。

While creating directory I am getting error below.

在创建目录时,我收到以下错误。

Error 1:

错误1:

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

不能在属性初始值设定项中使用实例成员'filemgr';属性初始化程序在'self'可用之前运行。

Error 2:

错误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.

谢谢。

4 个解决方案

#1


17  

Pls, write this code:

请写下这段代码:

Swift 3.0 And Swift 4.0

Swift 3.0和Swift 4.0

let documentsPath1 = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let logsPath = documentsPath1.appendingPathComponent("data")
    print(logsPath!)
    do {
        try FileManager.default.createDirectory(atPath: logsPath!.path, withIntermediateDirectories: true, attributes: nil)
    } catch let error as NSError {
        NSLog("Unable to create directory \(error.debugDescription)")
    } 

#2


24  

For Swift 4.0 Please use this

对于Swift 4.0,请使用此功能

    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)")
    }

#3


7  

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.

对于Swift 4.0,我创建了以下URL扩展,允许从应用程序中的文档目录创建文件夹。

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.

如果所需的文件夹不存在,它将创建它。然后,假设文件夹存在,它将URL返回给用户。否则,如果失败,则返回nil。

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

例如,要创建文件夹“MyStuff”,您可以这样调用它:

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

This would return:

这将返回:

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

文件:/// VAR /移动/容器/数据/应用/ 4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24 /文档/的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/

文件:///无功/移动/集装箱/数据/应用/ 4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24 /文档/我的/东西/这里/

#4


0  

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

你得到这个是因为你在错误的地方为newDir实例赋值。

I wrote your code in viewDidLoad and it works perfectly.

我在viewDidLoad中编写了你的​​代码,它运行得很好。

在Swift 3.0中创建目录

#1


17  

Pls, write this code:

请写下这段代码:

Swift 3.0 And Swift 4.0

Swift 3.0和Swift 4.0

let documentsPath1 = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let logsPath = documentsPath1.appendingPathComponent("data")
    print(logsPath!)
    do {
        try FileManager.default.createDirectory(atPath: logsPath!.path, withIntermediateDirectories: true, attributes: nil)
    } catch let error as NSError {
        NSLog("Unable to create directory \(error.debugDescription)")
    } 

#2


24  

For Swift 4.0 Please use this

对于Swift 4.0,请使用此功能

    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)")
    }

#3


7  

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.

对于Swift 4.0,我创建了以下URL扩展,允许从应用程序中的文档目录创建文件夹。

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.

如果所需的文件夹不存在,它将创建它。然后,假设文件夹存在,它将URL返回给用户。否则,如果失败,则返回nil。

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

例如,要创建文件夹“MyStuff”,您可以这样调用它:

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

This would return:

这将返回:

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

文件:/// VAR /移动/容器/数据/应用/ 4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24 /文档/的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/

文件:///无功/移动/集装箱/数据/应用/ 4DE0A1C0-8629-47C9-87D7-C2B4F3A16D24 /文档/我的/东西/这里/

#4


0  

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

你得到这个是因为你在错误的地方为newDir实例赋值。

I wrote your code in viewDidLoad and it works perfectly.

我在viewDidLoad中编写了你的​​代码,它运行得很好。

在Swift 3.0中创建目录