If you have an app that doesn’t use the internet or can’t use the internet but still want basic multi-language capability the below will help.
First add some labels and buttons. In adding the buttons add it twice (once as IBOutlet and then IBAction)
Create a JSON file, in my example I named mine data.json
{
"english":[
{
"Sunrise":"Sun Rise",
"Sunset":"Sunset",
"ShareBrief":"Share Brief",
"ShareDetailed":"Share Detailed"
}
],
"spanish":[
{
"Sunrise":"Salida del Sol",
"Sunset":"Puesta de Sol",
"ShareBrief":"Compartir Breve",
"ShareDetailed":"Compartir Detallado"
}
],
"french":[
{
"Sunrise":"Lever du Soleil",
"Sunset":"Le Coucher du Soleil",
"ShareBrief":"Partager Bref",
"ShareDetailed":"Partager Détaillé"
}
]
}
@IBAction func btnButtonTest(_ sender: Any) {
GetLanguage(language: "english");
}
@IBOutlet weak var btnButtonTestLabel: UIButton!
@IBAction func btnButtonTest1(_ sender: Any) {
GetLanguage(language: "spanish");
}
@IBOutlet weak var btnButtonTestLabel1: UIButton!
@IBOutlet weak var lblLabelTest: UILabel!
@IBOutlet weak var lblLabelTest1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Get device language
let dLanguageLocale = NSLocale.preferredLanguages[0]
print(dLanguageLocale);
let dLanguage = dLanguageLocale.components(separatedBy: "-")
switch (dLanguage[0])
{
case "en":
GetLanguage(language: "english");
case "es":
GetLanguage(language: "spanish");
case "fr":
GetLanguage(language: "french");
default:
GetLanguage(language: "english");
}
}
func GetLanguage(language: String)
{
if let path = Bundle.main.url(forResource: "data", withExtension: "json") {
do {
let jsonData = try Data(contentsOf: path, options: .mappedIfSafe)
do {
if let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? NSDictionary {
if let personArray = jsonResult.value(forKey: language) as? NSArray {
for (_, element) in personArray.enumerated() {
if let element = element as? NSDictionary {
let sSunrise = element.value(forKey: "Sunrise") as! String
print(sSunrise)
lblLabelTest4.text = sSunrise
let sSunset = element.value(forKey: "Sunset") as! String
print(sSunset)
lblLabelTest5.text = sSunset
let sBrief = element.value(forKey: "ShareBrief") as! String
print(sBrief)
btnButtonTestLabel.setTitle(sBrief, for: .normal)
let sDetailed = element.value(forKey: "ShareDetailed") as! String
print(sDetailed)
btnButtonTestLabel1.setTitle(sDetailed, for: .normal)
}
}
}
}
} catch let error as NSError {
print("Error: \(error)")
}
} catch let error as NSError {
print("Error: \(error)")
}
}
}
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.