OSDN Git Service

staticプロパティをインスタンスプロパティに変更
[kcd/KCD.git] / KCD / ApplicationDirecrories.swift
1 //
2 //  ApplicationDirecrories.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/08.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Foundation
10
11 private func supportDirName() -> String {
12     
13     let main = Bundle.main
14     
15     return main.bundleIdentifier
16         ?? main.infoDictionary?["CFBundleName"] as? String
17         ?? main.infoDictionary?["CFBundleExecutable"] as? String
18         ?? "UnknownAppliation"
19 }
20
21 func localizedAppName() -> String {
22     
23     guard let name = Bundle.main.localizedInfoDictionary?["CFBundleName"] as? String,
24         !name.isEmpty else {
25             
26             return supportDirName()
27     }
28     
29     return name
30 }
31
32 struct ApplicationDirecrories {
33     
34     static let shared = ApplicationDirecrories()
35     
36     let support = searchedURL(for: .applicationSupportDirectory)
37         .appendingPathComponent(supportDirName())
38     
39     let documents = searchedURL(for: .documentDirectory)
40     
41     let pictures = searchedURL(for: .picturesDirectory)
42     
43     static func searchedURL(for directory: FileManager.SearchPathDirectory) -> URL {
44         
45         return FileManager.default.urls(for: directory, in: .userDomainMask)
46             .last
47             ?? URL(fileURLWithPath: NSHomeDirectory())
48     }
49 }
50
51 extension ApplicationDirecrories {
52     
53     func createDirectory(_ url: URL) -> Bool {
54         
55         do {
56             
57             try FileManager.default.createDirectory(at: url,
58                                                     withIntermediateDirectories: false,
59                                                     attributes: nil)
60             
61             return true
62             
63         } catch {
64             
65             return false
66         }
67     }
68     
69     func checkDirectory(_ url: URL, create: Bool) -> Bool {
70         
71         do {
72             
73             let resourceValue = try url.resourceValues(forKeys: [.isDirectoryKey])
74             if !resourceValue.isDirectory! {
75                 
76                 print("Expected a folder to store application data, found a file \(url.path).")
77                 
78                 return false
79             }
80             
81             return true
82             
83         } catch let error as NSError {
84             
85             if create, error.code == NSFileReadNoSuchFileError {
86                 
87                 return createDirectory(url)
88             }
89             
90             return false
91         }
92     }
93 }