【发布时间】:2017-01-13 21:37:12
【问题描述】:
我创建了这个FileManager extension。有了这个extension,我想创建一个像这样的文件层次结构:
- 应用支持
- 收藏夹
- 饲料
- 图片
这是我在FileManagerextension 中的代码,我会在应用启动后立即调用app delegate。然后我将使用此代码始终检索文件夹的path。
这是创建此层次结构并在需要时检索路径的好方法吗?这是好习惯吗?
extension FileManager {
static func createOrFindApplicationDirectory() -> URL? {
let bundleID = Bundle.main.bundleIdentifier
// Find the application support directory in the home directory.
let appSupportDir = self.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
guard appSupportDir.count > 0 else {
return nil
}
// Append the bundle ID to the URL for the Application Support directory.
let dirPath = appSupportDir[0].appendingPathComponent(bundleID!)
// If the directory does not exist, this method creates it.
do {
try self.default.createDirectory(at: dirPath, withIntermediateDirectories: true, attributes: nil)
return dirPath
} catch let error {
print("Error creating Application Support directory with error: \(error)")
return nil
}
}
static func createOrFindFavoritesDirectory() -> URL? {
guard let appSupportDir = createOrFindApplicationDirectory() else {
return nil
}
let dirPath = appSupportDir.appendingPathComponent("Favorites")
// If the directory does not exist, this method creates it.
do {
try self.default.createDirectory(at: dirPath, withIntermediateDirectories: true, attributes: nil)
return dirPath
} catch let error {
print("Error creating Favorites directory with error: \(error)")
return nil
}
}
static func createOrFindFeedDirectory() -> URL? {
guard let appSupportDir = createOrFindFavoritesDirectory() else {
return nil
}
let dirPath = appSupportDir.appendingPathComponent("Feed")
// If the directory does not exist, this method creates it.
do {
try self.default.createDirectory(at: dirPath, withIntermediateDirectories: true, attributes: nil)
return dirPath
} catch let error {
print("Error creating Favorites directory with error: \(error)")
return nil
}
}
static func currentImagesDirectory() -> URL? {
guard let feedDir = createOrFindFeedDirectory() else {
return nil
}
let dirPath = feedDir.appendingPathComponent("Images")
// If the directory does not exist, this method creates it.
do {
try self.default.createDirectory(at: dirPath, withIntermediateDirectories: true, attributes: nil)
return dirPath
} catch let error {
print("Error creating Images directory with error: \(error)")
return nil
}
}
}
【问题讨论】:
-
我觉得不错。
-
@ILikeTau 谢谢!你有什么不同的做法吗?我希望看到其他一些示例,无论是您自己的代码还是与我正在尝试做的事情类似的教程/链接。
-
我可能会将
createOrFindFavoritesDirectory()和createOrFindFeedDirectory()组合成一个带参数的函数,但除此之外,它看起来都很好。 -
@ILikeTau 你能发布一个答案吗?我只是很想知道其他人会如何做到这一点——尝试向比我更好的人学习:)
标签: ios objective-c swift extension-methods nsfilemanager