I am trying to implement a function that can change app language.
I tried to set it like this:
let defaults = NSUserDefaults.standardUserDefaults()
defa
Updated Swift syntax of the main.swift
file mentioned in @royherma's answer. This will avoid having to restart the app after overriding the UserDefaults settings:
import Foundation
import UIKit
// Your initialization code here
let langCultureCode: String = "LANGUAGE_CODE"
UserDefaults.standard.set([langCultureCode], forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))
paired together with the removal of @UIApplicationMain
in your AppDelegate.swift
file.
If mean for test purpose, just change the language in simulator settings app.
If you are trying to make a sort of language selector in your app, it' pretty painful and in my opinion you should not.
Your app reads language and locale settings from the device and change the UI accordingly.
Override this behavior is tough and you will never accomplish a full change in language, for instance if you try to display a map in you app and your device language is Spanish, but the app language is english, you will see the map indications written in Spanish.
Here a project that could help.
You have to set the AppleLanguages
key with an array, not a string:
UserDefaults.standard.set(["de"], forKey: "AppleLanguages")
You may try below in AppDelegate.swift though changes will not appear instantly but after you kill and relaunch your app. -
NSUserDefaults.standardUserDefaults().removeObjectForKey("AppleLanguages")
NSUserDefaults.standardUserDefaults().setObject(["de"], forKey: "AppleLanguages"
NSUserDefaults.standardUserDefaults().synchronize()
Yes you can change the app language immediately like,
var language = "de"
let path = NSBundle.mainBundle().pathForResource(language, ofType: "lproj")
let bundle = NSBundle(path: path!)
let string = bundle?.localizedStringForKey("key", value: nil, table: nil)
use your NSUserDefaults value to language.
Here is how you change the language prior to launch in swift
-
Lets say i want to force Hebrew
localization:
import Foundation
import UIKit
// Your initialization code here
let langCultureCode: String = "he_IL"
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject([langCultureCode], forKey: "AppleLanguages")
defaults.synchronize()
UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))
//@UIApplicationMain <-- COMMENT THIS OUT
class AppDelegate: UIResponder, UIApplicationDelegate
This will make your app forced to a locale WITHOUT needing any launch