2017-01-13 3 views
0

Я создал это FileManagerextension. С этой extension, я хочу создать иерархию файлов следующим образом:iOS - Лучшие практики для расширений FileManager

  • Поддержка приложений
    • Избранное
    • Feed
      • Изображения

Это код, который я имею в 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 
     } 
    } 
} 
+0

Выглядит хорошо для меня. –

+0

@ILikeTau Спасибо! Есть ли что-то другое? Я хотел бы увидеть некоторые другие примеры, поместить свой собственный код или учебник/ссылку, которая имеет нечто похожее на то, что я пытаюсь сделать. – JEL

+0

Я мог бы комбинировать 'createOrFindFavoritesDirectory()' и 'createOrFindFeedDirectory()' в одну функцию, которая принимает аргумент, но кроме этого все это выглядит нормально. –

ответ

1

Это выглядит довольно хорошо, но вы могли бы объединить немного кода и имеют лучшую проверку ошибок:

extension FileManager { 
    static func createOrFindApplicationDirectory() -> URL? { 
     guard let bundleID = Bundle.main.bundleIdentifier else { 
      return nil 
     } 

     // Find the application support directory in the home directory. 
     let appSupportDirArray = self.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) 

     guard let appSupportDir = appSupportDirArray.first else { 
      return nil 
     } 

     // Append the bundle ID to the URL for the Application Support directory. 
     let dirPath = appSupportDir.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 createOrFindDirectory(named name: String) -> URL? { 
     guard let appSupportDir = createOrFindApplicationDirectory() else { 
      return nil 
     } 

     let dirPath = appSupportDir.appendingPathComponent(name) 

     // 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 \(name) directory with error: \(error)") 
      return nil 
     } 
    } 

    static func currentImagesDirectory() -> URL? { 
     guard let feedDir = createOrFindDirectory(named: "Feed") 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 
     } 
    } 
} 
+0

Выглядит неплохо! Я вижу, что вы объединили Feed и Favorite в одну функцию 'static func createOrFindDirectory (с именем name: String) -> URL?', Cool. Что касается «проверки ошибок», мне действительно нужны эти папки/каталоги, которые будут созданы при первом запуске приложения. Как вы обрабатываете ошибку, кроме того, что возвращаете 'nil', чтобы я гарантировал, что эти папки создаются до их разработки? Точка, без этих папок, созданных при запуске приложения, мое приложение не будет работать правильно – JEL

+0

Поскольку вы упомянули об обработке ошибок, мне стало больше думать. Я не уверен, когда именно «создание» одной из этих папок может потерпеть неудачу, но в в этом случае он не уверен, как справиться с этим, чтобы приложение не прогрессировало до тех пор, пока оно не будет создано – JEL