IOS build phase auto localization of permission (React native)

Spread the love

The problem is we don’t want to maintain the translations at two places. One in ‘.json’ files in Javascript and other in ‘xx.lproj/InfoPlist.strings’ files.

The following code will help you auto copy the permissions. You may need to modify it somewhat.

# Type a script or drag a script file from your workspace to insert its path.
langFiles=("en" "en" "ar" "es" "ja" "ko" "mn" "my" "ru" "th" "vi" "zh_my" "zh")
targetFiles=("en" "English" "ar" "es" "ja" "ko" "mn" "ms" "ru" "th" "vi" "my" "zh")
keys=("common.permissionIOS.camera" "common.permissionIOS.microphone" "common.permissionIOS.photoLibrary" "common.permissionIOS.contacts")
permissionName=("NSCameraUsageDescription" "NSMicrophoneUsageDescription" "NSPhotoLibraryUsageDescription" "NSContactsUsageDescription")
for index in "${!langFiles[@]}"; do
  #Copy specific keys values from langFiles to targetFiles
  #Don't add any space before 'END'. Otherwise it will be considered as text and not the end.
  localizedFileContent=$(cat <<-END
    /* 
      Copyright © Company. All rights reserved.
   */
END
)
   for keyIndex in "${!keys[@]}"; do
      #read key line from json
      langPath="$PROJECT_DIR/../app/i18n/resources/${langFiles[$index]}.json"
      line=$(grep ${keys[$keyIndex]} $langPath)
      #split line
      splitKeyValue=$(echo $line | cut -d ":" -f 2)
      #try remove spaces and ',' from end
      value=$(echo ${splitKeyValue} | sed -E 's/[,\s\r\n]+$//g')
      #${main_string/search_term/replace_term}
      value=${value/,/} # for unicode characters, sed command not working. so removing ',' other way
      value=$(echo $value|tr -d '\r\n')
      value=$(echo $value|tr -d '\n')
      #append to localizedFileContent
      echo "$localizedFileContent"
      localizedFileContent="${localizedFileContent}\n${permissionName[$keyIndex]}=$value;"
   done
   echo "$localizedFileContent"
   #Save the localizedFileContent to targetFile
   targetFilePath="$PROJECT_DIR/${targetFiles[$index]}.lproj/InfoPlist.strings"
   echo "$localizedFileContent" > "$targetFilePath"
done

Cheers and Peace out!!!