OSDN Git Service

shared instanceを持つようにした
[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     static let support = searchedURL(for: .applicationSupportDirectory)
37         .appendingPathComponent(supportDirName())
38     
39     static let documents = searchedURL(for: .documentDirectory)
40     
41     static let pictures = searchedURL(for: .picturesDirectory)
42     
43     private 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
52 func createDirectory(_ url: URL) -> Bool {
53     
54     do {
55         
56         try FileManager.default.createDirectory(at: url,
57                                                 withIntermediateDirectories: false,
58                                                 attributes: nil)
59         
60         return true
61         
62     } catch {
63         
64         return false
65     }
66 }
67
68 func checkDirectory(_ url: URL, create: Bool) -> Bool {
69     
70     do {
71         
72         let resourceValue = try url.resourceValues(forKeys: [.isDirectoryKey])
73         if !resourceValue.isDirectory! {
74             
75             print("Expected a folder to store application data, found a file \(url.path).")
76             
77             return false
78         }
79         
80         return true
81         
82     } catch let error as NSError {
83         
84         if create, error.code == NSFileReadNoSuchFileError {
85             
86             return createDirectory(url)
87         }
88         
89         return false
90     }
91 }