Created
July 16, 2017 00:40
-
-
Save KrisYu/b94f79ad3d356d7e7f20356e467aeed3 to your computer and use it in GitHub Desktop.
A simple class to read and write to a specific plist.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
class LogFile { | |
static var logPath: String? { | |
get { | |
let paths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, | |
.userDomainMask, | |
true) | |
let supportDirectory = paths.first! + "/Pomodoro/" | |
do { | |
try FileManager.default.createDirectory(atPath: supportDirectory, withIntermediateDirectories: true, attributes: nil) | |
let filePath = supportDirectory + "/storage.plist" | |
return filePath | |
} catch { | |
debugPrint(error.localizedDescription) | |
return nil | |
} | |
} | |
} | |
static var dateFormatter: DateFormatter = { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = "MM/dd/yyyy" | |
return dateFormatter | |
}() | |
static func readFromLog(today: Date) -> Int { | |
let fileMangaer = FileManager.default | |
let strDay = dateFormatter.string(from: today) | |
guard let logPath = logPath else { return 0 } | |
if fileMangaer.fileExists(atPath: logPath) { | |
let plistContent = NSDictionary.init(contentsOfFile: logPath) as! [String: Int] | |
if plistContent[strDay] != nil { | |
return plistContent[strDay]! | |
} | |
} else { | |
fileMangaer.createFile(atPath: logPath, contents: nil, attributes: nil) | |
let logDict = NSDictionary.init(dictionary: [strDay: 0]) | |
logDict.write(toFile: logPath, atomically: true) | |
} | |
return 0 | |
} | |
static func writeToLog(today: Date, finished: Int) { | |
guard let logPath = logPath else { return } | |
var logDict = NSDictionary.init(contentsOfFile: logPath) as! [String: Int] | |
let strDay = dateFormatter.string(from: today) | |
logDict[strDay] = (logDict[strDay] ?? 0) + finished | |
let logNSDict = NSDictionary.init(dictionary: logDict) | |
logNSDict.write(toFile: logPath, atomically: true) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment