私はこれを作成しましたFileManager
extension
このextension
で、私はそうのようなファイル階層を作成したい:iOS - FileManager拡張のベストプラクティス
- アプリケーションサポート
- お気に入り
- フィード
- 画像
これは、FileManager
extension
のコードです。これは、アプリケーションが起動するとすぐに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ありがとう!あなたは何か違うことはありますか?自分のコードやチュートリアル/リンクなど、私がやろうとしているものに似た何か他の例を見たいと思っています。 – JEL
私は、 'createOrFindFavoritesDirectory()'と 'createOrFindFeedDirectory()'を引数を取る一つの関数に組み合わせることができますが、それ以外はすべてうまく見えます。 –