Temporary file path using swift

2020-06-30 05:22发布

How to get a unique temporary file path using Swift/Cocoa on OS X? Cocoa does not seem to provide a function for this, only NSTemporaryDirectory() which returns the path of the temporary directory. Using the BSD mktemp function requires a mutable C-string as argument.

8条回答
我欲成王,谁敢阻挡
2楼-- · 2020-06-30 05:58

FileManager extension in Swift to get a temporary file URL. You can pass your own file name and extension, if needed.

public extension FileManager {

    func temporaryFileURL(fileName: String = UUID().uuidString) -> URL? {
        return URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(fileName)
    }
}

Usage:

let tempURL = FileManager.default.temporaryFileURL()
let tempJPG = FileManager.default.temporaryFileURL(fileName: "temp.jpg")
查看更多
Deceive 欺骗
3楼-- · 2020-06-30 06:01

Swift3

I came here looking for something like boost::filesystem::unique_path()

So I made this extension to the URL class.

extension URL {
    func appendingUniquePathComponent(pathExtension: String? = nil) -> URL {
        var pathComponent = UUID().uuidString
        if let pathExtension = pathExtension {
            pathComponent += ".\(pathExtension)"
        }
        return appendingPathComponent(pathComponent)
    }
}

Usage:

let url0 = URL(fileURLWithPath: "/tmp/some/dir")
let url1 = url0.appendingUniquePathComponent(pathExtension: "jpg")
print("url1: \(url1)")
// url1: file:///tmp/some/dir/936324FF-EEDB-410E-AD09-E24D5EB4A24F.jpg
查看更多
登录 后发表回答