Reputation: 905
I have a struct for my local notifications, with an init
that goes into localizable.strings and assigns the value corresponding to key
to the body of the notification:
struct Notification {
let identifier: String
let body: String
init(withKey: String) {
self.id = key
self.body = NSString.localizedUserNotificationString(forKey: key, arguments: nil)
}
So if my localizable.strings looks like this:
"testKey" = "Test Notification";
Then initializing a new Notification
object will yield the following:
let notification = Notification(withKey: "testKey")
print(notification.body) // prints "Test Notification"
However, if I initialize the notification with a typo, the body is just going to be the mistyped key:
let mistypedNotification = Notification(withKey: "tstKey")
print(mistypedNotification.body) // prints "tstKey"
My desired behaviour is to have a default string be assigned to the body of the notification if the initializer is called with a key that does not currently exist in localizable.strings, as below:
let desiredNotification = Notification(withKey: "keyNotCurrentlyInLocalizableFile")
print(desiredNotification.body) // prints "default string"
I know this can be achieved using one of the NSLocalizedString
initializers, but in doing so, I would give up the benefits of using NSString.localizedUserNotificationString
, which I don't want to do. Is there any way to achieve my desired behaviour without tapping into NSLocalizedString
?
Upvotes: 2
Views: 719
Reputation: 5954
There's a small drawback with the solution proposed by @Sh_Khan. If you don't have a translation for one of user's preferred languages at the time when the notification is created, then default value will be displayed. If later user adds a new language that your app supports, existing notifications won't adapt their strings to it as it's supposed to work with localizedUserNotificationString
.
Sadly, Apple doesn't seem to support a direct way of supplying default values for localized notification strings as it does for normal localized strings.
I'd suggest just using your default values as keys where possible for notifications. And where it's not possible use the solution by @Sh_Khan.
Upvotes: 0
Reputation: 100503
When there is no key/value for the string in defaults , it returns the same string you specify so if they are equal that means you can specify a default value
let possibleBody = NSString.localizedUserNotificationString(forKey: key, arguments: nil)
self.body = possibleBody == key ? "defaultValue" : possibleBody
Upvotes: 2