iOS app test if Localization translations have same keys - ios

In my iOS app I have localization files such as Localizable.strings.
I want to check that they have same keys and there is no missed keys in each localization.
I thought about performing this in Unit Tests.
Is Unit testing the right place for this? Maybe there is much easier tool for it?
How this Unit testing can be done?
I found article on this topic in Obj-C https://www.cocoanetics.com/2013/03/localization-unit-test/ that is 5 years old. Maybe something else can be used?

You can just use this shell script I made up and run it as a Run Script (within Build Phases) of your App Target.
First, create the shell script and save it somewhere in your App Project, I saved it as check_missing_keys_in_translations.sh for example:
#!/bin/sh
# check_missing_keys_in_translations.sh
#
# Overview: Script will be executed from Build Phases > Run Script
#
# Script: Extract sorted localization keys using "$1" as language code
# given as parameter to locate the right Localizable.strings.
#
# Build Phases > Run Script: The result will be compared to see if
# translations have the same keys or if one of them have more or less.
plutil -convert json 'AppProject/Resources/Localization/'"$1"'.lproj/Localizable.strings' -o - | ruby -r json -e 'puts JSON.parse(STDIN.read).keys.sort'
Just change the path AppProject/Resources/Localization/ to the path where your en.lproj, it.lproj... localization folders are located in your app (in this case called AppProject).
Second, go to your App Project, select the App Target and under Build Phases put this script code within Run Script:
# Check missing localization keys in translations
MISSING_KEYS_TRANSLATIONS=$(diff <($SRCROOT/tools/localization/check_missing_keys_in_translations.sh en) <($SRCROOT/tools/localization/check_missing_keys_in_translations.sh it))
if [ "$MISSING_KEYS_TRANSLATIONS" ]; then
echo "warning: $MISSING_KEYS_TRANSLATIONS"
fi
As always, check the path and adapted to where you saved the script created before. I saved it under App Project/tools/localization/... as you can see. You might want to adapt this script to better reflect your situation as I had only 2 localizable I was interested in checking they had the same keys. Is just shell scripting.
Check screenshot below:

Related

iOS Sourcery with Flutter build

Im trying to build my flutter app for iOS it has a google maps key that I want to protect and not check in to source control it needs to be buildable from azure, to achieve this I'm storing my maps key as a secret variable in azure and as a system environment variable locally, I'm using Sourcery https://github.com/krzysztofzablocki/Sourcery to generate a class for me that contains this key, it all works but only the second time I build, the first build always fails.
So I'm building using this command
flutter build ios --flavor dev --verbose
Which the first run will give me the error
error: Build input file cannot be found:
'/Users/martin/xxx/xxx/xxx/ios/Runner/Credentials.generated.swift' (in target
'Runner'
Then issuing the same command again
** BUILD SUCCEEDED **
this is my run script its called before compile sources and after the flutter run script
this calls my script which calls another script to export the map api key and runs sourcery command using a .yml file as its config heres the script, (it also does some logging)
#!/bin/bash
echo "Generate Credentials Code"
CREDENTIALS_DIR="$SRCROOT/credentials"
# Set credentials if local script for adding environment variables exist
if [ -f "$CREDENTIALS_DIR/add_credentials_to_env.sh" ]; then
echo "Add credentials to environement"
source "$CREDENTIALS_DIR/add_credentials_to_env.sh"
echo "finished running add_credentials_to_env.sh"
fi
echo "RUN SOURCERY"
$SRCROOT/Pods/Sourcery/bin/sourcery --config "$SRCROOT/config.yml"
echo "FINISHED RUNNING SOURCERY"
for file in "$SRCROOT/Runner"/*; do
echo "$file"
done
and here is my config file
sources:
- .
project:
file: Runner.xcodeproj
target:
name: Runner
module: Runner
templates:
- credentials/Credentials.stencil
output:
path: ./Runner/
link:
project: Runner.xcodeproj
target: Runner
args:
mapsApiKey: ${MAPS_API_KEY_IOS}
this generates my class correctly on the first build and seems to be added correctly to the target (edited out my key) but the app will only compile if I run the build command again.
// Generated using Sourcery 1.4.2 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
public struct Credentials {
let mapsApiKey: String
}
public let credentials = Credentials(mapsApiKey:
"xxxxxxxxxxMY_KEYxxxxxxxxxxx")
Any ideas?
xcode 12.5 m1 macbook pro, swift 5
Looks like you generate the file too late. I'll suggest move your script to Aggregate and add it as a dependency to your target
Add Aggregate
Move your script to 'Run script' section
Add 'PreBuildScriptsRunner' as a dependency to your application target, make sure 'Dependencies' section on top of all other sections
Manually setting environment variables is an annoying thing developers would have to do on their own machines, and there are nicer/ more common ways of setting up private keys. After a few years of using environment variables/ bash, it still causes issues which are not easily detectable. You may want to automate/ document it, but then you have to consider developers using zsh, fish vs. bash? Also, I try to avoid using Xcode build phases where possible.
Solution? (This is what I have)
Why don't you use your CI (Azure pipeline?, I use Github workflows) to write a Xcode build configuration file (not a Swift file). The sensitive keys could be in a file Secrets.xcconfig, which is added to your Xcode as a build configuration. Then, in your Info.plist of your application, and your code can load them.
Create a file, Secrets.xcconfig:
SECRET_API_KEY = 12312rfiwhvde.wvascafsf.df325
Add it to your Xcode project, and then to the project's build configuration:
Add Secrets.xcconfig to your .gitignore
Make sure to git ignore the file before committing it to the repo. You can also keep an Example.Secrets.xcconfig which users can use. In the readme, tell users to run cp Example.Secrets.xcconfig Secrets.xcconfig and then to update values in it. Now you can clearly see what keys the application is using (its clearly in the directory). As a bonus, you can add this file the Xcode project, so that when the file is missing, it shows up in red (indicating to the user they really should acquire this file somehow):
In Info.plist, reference the variable:
<dict>
<key>SECRET_API_KEY</key>
<string>$(SECRET_API_KEY)</string>
</dict>
In your code, load the variable that was stored in Info.plist:
let key = Environment.infoDictionary["SECRET_API_KEY"] as? String
In your CI/ Azure pipeline:
Run echo "SECRET_API_KEY = $SECRET_API_KEY_SAVED_IN_CONTINUOUS_INTEGRATION" >> Secrets.xcconfig
Then you can just .gitignore the file instead of setting environment variables. When you work with other developers, you just give them this file, and nothing else needs to be done to build locally.
So I have answered your question not by solving your direct problem, but giving you a more common/ canonical way of solving this problem that many developers have faced before.

Use name with whitespace for qmake TARGET variable

iOS/OS X application names usually contains spaces (like "App Store.app").
But when i'm trying to use such name in my Qt/ios project like this:
ios: TARGET = "My Cool App"
build process failed with strange error in the autogenerated by Qt Bash script.
Am i doing something wrong, or such whitespaces in names just don't supported?
UPD
the problem first time occurs in qmake-generated shell script:
#!/bin/sh
cp -r $BUILT_PRODUCTS_DIR/$FULL_PRODUCT_NAME /Users/eraxillan/Projects/<PROJECT_DIR>
If $FULL_PRODUCT_NAME contains spaces, then script just fails.
Script generated and executed only in case of custom DESTDIR project variable value - my case.
So, looks like a bug in qmake-generated script to copy project build artefacts to custom output directory.
Workarounds:
Remove spaces from target name (My Cool App --> my-cool-app)
Do not use custom DESTDIR value at all
Hope this will be helpful
This should work:
TARGET = My" "Cool" "App

Different Application Name For Development/Release Build

I have an iOS application that has "sysadmin" only features when in the development build which are removed for the release build.
What is the easiest way to have two builds on our testing devices in house, one in development mode, and one in release mode that have different names on the iOS home screen?
The current situation is that when we want to test the release build, I have to manually rebuild it for each device. When we want to switch back, I have to once again manually rebuild the application.
As LoVo mentioned - you will need different app-identifiers and bundle display names. Here's how I would approach the problem:
In Project's build settings set the following values:
Preprocess Info.plist File - Yes
Info.plist Preprocessor Prefix File - InfoPlist_proc.h
Add the header generation script to your Xcode project.
The script in ruby should look like this:
#!/usr/bin/env ruby
# build type is going to be passed
build_type = ENV["CONFIGURATION"]
proc_header_path = File.join(ENV["SRCROOT"], "InfoPlist_proc.h")
File.open(proc_header_path, "w+") do |f|
f.write("#define BUNDLE_IDENTIFIER com.company.app.#{ build_type.downcase }\n")
f.write("#define BUNDLE_DISPLAY_NAME \"My App #{ build_type.downcase }\"")
end
Now in the "Build" stage of your scheme (Cmd+Shift+,) create "Run Script" pre-action:
Add execution permissions to previously created script ($ chmod a+x script.rb) and set it to run from your pre-build script run phase:
Finally in your current Info.plist file change the bundle identifier and display name values with preprocessor definitions:
Now each time you build your app, the InfoPlist_proc.h file will be regenerated. This has a drawback though: to change your app's bundle identifier or name you would have to edit the script, not the Info.plist
But it also gives an advantage: you can inject the bundle version and short version string from what your cvs gives you. I usually use git rev-list --count --all for bundle version and git describe --tags --first-parent for short version string.
Hope this helps.
Set different App-Identifiers and Bundle Display Names

Get XCODE to Copy run script converted files to iOS resources bundle?

I have a script which converts wav files to caf files, and I'd like to get them copied to my iOS app automatically. The script looks like this:
Xcode doesn't copy it automatically, and i can't find a way to add it to my Copy Build Phase section. It appears that I need to add a line in the script to copy it directly to the app bundle, or to make the destination the app bundle itself.
What would that script/change be? I'm not sure what shell vars to use for the cp command.
Thanks - Henry
The environment variable you're looking for is "BUILT_PRODUCTS_DIR" and you can find the definition of this, and plenty of other useful Xcode-specific environment variables on this handy Apple documentation page.
And what you'd probably want to do is test for the existence of successfully converted files, and if they exist, then copy those files into the "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}" directory.

Modifying Info.plist's CFBundleVersion in Xcode 5 with Asset Library enabled

With Xcode 5's new Asset Library, adding images and organizing them has never been easier. However, it seems as if it has broken some scripts I use for creating builds.
I have a script within my Run Script Phase that sets the CFBundleVersion to be the current timestamp within the plist. In the script, I execute this statement:
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $timestamp" $BUILT_PRODUCTS_DIR/$INFOPLIST_PATH
However, when this gets executed, the following statement displays:
Set: Entry, ":CFBundleVersion", Does Not Exist
File Doesn't Exist, Will Create: /Users/SpacePyro/Library/DerivedData/BundleTest-duikdqngfmrovnagrcsvdcuxxstz/Build/Products/Debug-iphoneos/BundleTest.app/Info.plist
It seems like this happens on clean builds. The plist doesn't seem to get generated until midway through the build, presumably due to the Asset Libraries.
I've also used this command, and while it doesn't throw the error, it still blows away my changes (assume INFO_PLIST="${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/Info"):
defaults write $INFO_PLIST CFBundleVersion $timestamp
This used to not be the case when I started using the Asset Library to organize my app icons and splash images. Anyone know why this happens? And better yet, is there a workaround to add this value to the plist? I've already tried placing the script in a pre-action build phase, as well as the post-action build phase. I've also tried running the command after the build has completed, but when I try to codesign and package it up, it says that the signature is invalid due to plist modification.
If no reasonable solution exists, I guess I could always de-migrate from Asset Libraries until I can get my scripts to work.
I had similar issue once, and here is what finally helped me out:
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${INFOPLIST_FILE}")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "${INFOPLIST_FILE}"
(Use INFOPLIST_FILE directly, not $BUILT_PRODUCTS_DIR/$INFOPLIST_PATH)
Hope this could be useful .
Figured this one out, and it was a silly one. Turns out you can just move the script phase to the very end. I didn't even know these were movable, or that it mattered! But by dragging the Run Script phase to the bottom as such, the scripts were able to run and modify things as needed.
I had the same problem, In my case, I had a wrong file path to the XXX-Info.plist file:
Build Settings -> Packaging -> Info.plist File
I changed it it's actual location and start working.
If your plist file is Preprocessed-Info.plist, then change the value of "Preprocess Info.plist File" (INFOPLIST_PREPROCESS) to "Yes" (true) like this:
Search in Build settings for $(SRCROOT) and remove it.
transform it from
$(SRCROOT)/TestProject/Info.plist
to
TestProject/Info.plist

Resources