Skip to content

Instantly share code, notes, and snippets.

@Gujci
Created May 11, 2016 11:57
Show Gist options
  • Save Gujci/550d04b1cde3ee95de1cb1eeaa762059 to your computer and use it in GitHub Desktop.
Save Gujci/550d04b1cde3ee95de1cb1eeaa762059 to your computer and use it in GitHub Desktop.
import Foundation
public extension String {
var localized: String {
return LocalizationManager.sharedInstance.getTranslation(forText: self) ?? self
}
}
class LocalizationManager {
static let sharedInstance = LocalizationManager()
var localizationFilePath: String?
private lazy var localicationParsedDictionary: Dictionary<String, String> = {
if let path = self.localizationFilePath {
if let validFormatDictionary = NSDictionary(contentsOfFile: path) as? Dictionary<String, String> {
return validFormatDictionary
}
else {
fatalError("Invalid plist format at file path.")
}
}
else {
fatalError("Localization File Path is not set.")
}
}()
func getTranslation(forText text: String) -> String? {
return localicationParsedDictionary[text]
}
func updateTranslations() {
unowned let welf = self
let translationDownloader = API(withBaseUrl: "TODO")
translationDownloader.get("/TODO") { err, data in
guard err == nil else { return }
if let translationJSONData = data {
translationJSONData.forEach() { translationPair in
welf.localicationParsedDictionary[translationPair.0] = translationPair.1.stringValue
}
if let setFilePath = welf.localizationFilePath,
let translationsData = try? NSPropertyListSerialization.dataWithPropertyList(welf.localicationParsedDictionary,
format: .XMLFormat_v1_0, options: 0) {
translationsData.writeToFile(setFilePath, atomically: true)
}
}
}
}
init() {
updateTranslations()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment