Localization

WorldTrotter is now internationalized – its interface is able to adapt to various languages and regions. Now it is time to localize the app – that is, to update the strings and resources in the application for a new language. In this section, you are going to localize the interface of WorldTrotter: the Main.storyboard file. You will create English and Spanish localizations, which will create two lproj directories in addition to the base one.

Start by localizing a storyboard file. Select Main.storyboard in the project navigator.

Open the file inspector by clicking the File inspector icon is shown. tab in the inspector selector or by using the keyboard shortcut Option-Command-1. Find the section in this inspector named Localization. Check the English box and make sure that the dropdown says Localizable Strings (Figure 7.13). This will create a strings table that you will use later to localize the application.

Figure 7.13  Localizing into English

Screenshot of the Preview pop-up menu from the Editor area jump bar is shown. The last item on the menu is “Preview” is selected which has a single item “Main. storyboard preview.”

Next, in the project navigator, select the WorldTrotter project at the top. Then select WorldTrotter under the Project section in the side list, and make sure the Info tab is open. (If you cannot see the side list, you can open it using the Show projects and targets list button in the upper-left corner (Figure 7.14).)

Figure 7.14  Showing the project settings

Screenshot of the Project Navigator listing Project and Targets. An icon at the top right is labeled “Show or Hide projects and targets list.”

Click the + button under Localizations and select Spanish (es). In the dialog, you can uncheck the LaunchScreen.storyboard file; keep the Main.storyboard file checked. Make sure that the reference language is Base and the file type is Localizable Strings. Click Finish. This creates an es.lproj folder and generates the Main.strings file in it that contains all the strings from the base interface file. The Localizations configuration should look like Figure 7.15.

Figure 7.15  Localizations

Screenshot displaying the Localization Configuration Settings.

Look in the project navigator. Click the disclosure button next to Main.storyboard (Figure 7.16). Xcode moved the Main.storyboard file to the Base.lproj directory and created the Main.strings file in the es.lproj directory.

Figure 7.16  Localized storyboard in the project navigator

Screenshot of the project navigator with the Main.storyboard expanded, which lists three components: Main.storyboard (base), Main.strings (English), and Main.storyboard (Spanish).

Click on the Spanish version of Main.strings. When this file opens, the text is not in Spanish. You have to translate localized files yourself; Xcode is not that smart.

Edit this file according to the following text. The numbers and order may be different in your file, but you can use the text and title fields in the comments to match up the translations.

/* Class = "UITabBarItem"; title = "Map"; ObjectID = "6xh-o5-yRt"; */
"6xh-o5-yRt.title" = "Map" "Mapa";

/* Class = "UILabel"; text = "degrees Celsius"; ObjectID = "7la-u7-mx6"; */
"7la-u7-mx6.text" = "degrees Celsius" "grados Celsius";

/* Class = "UILabel"; text = "degrees Fahrenheit"; ObjectID = "Dic-rs-P0S"; */
"Dic-rs-P0S.text" = "degrees Fahrenheit" "grados Fahrenheit";

/* Class = "UILabel"; text = "100"; ObjectID = "Eso-Wf-EyH"; */
"Eso-Wf-EyH.text" = "100";

/* Class = "UITextField"; placeholder = "value"; ObjectID = "On4-jV-YlY"; */
"On4-jV-YlY.placeholder" = "value" "valor";

/* Class = "UILabel"; text = "is really"; ObjectID = "wtF-xR-gbZ"; */
"wtF-xR-gbZ.text" = "is really" "es realmente";

/* Class = "UITabBarItem"; title = "Convert"; ObjectID = "zLY-50-CeX"; */
"zLY-50-CeX.title" = "Convert" "Convertir";

Now that you have finished localizing this storyboard file, let’s test it out. First, there is a little Xcode glitch to be aware of: Sometimes Xcode ignores a resource file’s changes when you build an application. To ensure that your application is being built from scratch, first delete it from your device or simulator. (Press and hold its icon in the launcher. When it starts to wiggle, tap the delete badge.) Relaunch Xcode. (Yes, exit and start it again.) Then, choose Clean from the Product menu. Finally, to be absolutely sure, press and hold the Option key while opening the Product menu and choose Clean Build Folder.... This will force the application to be entirely recompiled, rebundled, and reinstalled.

Open the active scheme pop-up and select Edit Scheme. Make sure Run is selected on the lefthand side and open the Options tab. Open the Application Language pop-up and select Spanish. Finally, confirm that Spain is still selected from the Application Region pop-up. Close the window.

Build and run the application. Make sure you are viewing the ConversionViewController, and you will see the interface in Spanish. Because you set the constraints on the labels to accommodate different lengths of text, they resize themselves appropriately (Figure 7.17).

Figure 7.17  Spanish ConversionViewController

Screenshot of the Conversion View Controller with Spanish text in its labeled.

NSLocalizedString and strings tables

In many places in your applications, you create String instances dynamically or display string literals to the user. To display translated versions of these strings, you must create a strings table. A strings table is a file containing a list of key-value pairs for all of the strings that your application uses and their associated translations. It is a resource file that you add to your application, but you do not need to do a lot of work to get data from it.

You might use a string in your code like this:

let greeting = "Hello!"

To internationalize the string in your code, you replace literal strings with the function NSLocalizedString(_:comment:).

let greeting = NSLocalizedString("Hello!", comment: "The greeting for the user")

This function takes two arguments: a key and a comment that describes the string’s use. The key is the lookup value in a strings table. At runtime, NSLocalizedString(_:comment:) will look through the strings tables bundled with your application for a table that matches the user’s language settings. Then, in that table, the function gets the translated string that matches the key.

Now you are going to internationalize the strings that the MapViewController displays in its segmented control. In MapViewController.swift, locate the loadView() method and update the initializer for the segmented control to use localized strings.

override func loadView() {
    // Create a map view
    mapView = MKMapView()

    // Set it as *the* view of this view controller
    view = mapView

    let segmentedControl
            = UISegmentedControl(items: ["Standard", "Satellite", "Hybrid"])

    let standardString = NSLocalizedString("Standard", comment: "Standard map view")
    let satelliteString
            = NSLocalizedString("Satellite", comment: "Satellite map view")
    let hybridString = NSLocalizedString("Hybrid", comment: "Hybrid map view")
    let segmentedControl
          = UISegmentedControl(items: [standardString, satelliteString, hybridString])

Once you have files that have been internationalized with the NSLocalizedString(_:comment:) function, you can generate strings tables with a command-line application.

Open the Terminal app. This is a Unix terminal; it is used to run command-line tools. You want to navigate to the location of MapViewController.swift. If you have never used the Terminal app before, here is a handy trick. In Terminal, type the following:

cd

followed by a space. (Do not press Return yet.)

Next, open Finder and locate MapViewController.swift and the folder that contains it. Drag the icon of that folder onto the Terminal window. Terminal will fill out the path for you. It will look something like this:

cd /Users/cbkeur/iOSDevelopment/WorldTrotter/WorldTrotter/

Press Return. The current working directory of Terminal is now this directory.

Use the terminal command ls to print out the contents of the working directory and confirm that MapViewController.swift is in that list.

To generate the strings table, enter the following into Terminal and press Return:

genstrings MapViewController.swift

The resulting file, Localizable.strings, contains the strings from MapViewController. Drag this new file from Finder into the project navigator (or use the FileAdd Files to "WorldTrotter"... menu item). When the application is compiled, this resource will be copied into the main bundle.

Open Localizable.strings. The file should look something like this:

/* Hybrid map view */
"Hybrid" = "Hybrid";

/* Satellite map view */
"Satellite" = "Satellite";

/* Standard map view */
"Standard" = "Standard";

Notice that the comment above your string is the second argument you supplied to the NSLocalizedString function. Even though the function does not require the comment argument, including it will make your localizing life easier.

Now that you have created Localizable.strings, you need to localize it in Xcode. Open its file inspector and click the Localize... button in the utility area. Make sure Base is selected from the pop-up and click Localize. Add the Spanish and English localization by checking the box next to each language.

In the project navigator, click on the disclosure triangle that now appears next to Localizable.strings. Open the Spanish version. The string on the lefthand side is the key that is passed to the NSLocalizedString(_:comment:) function, and the string on the righthand side is what is returned. Change the text on the righthand side to the Spanish translations shown below. (To type an accented character, such as “é,” press and hold the appropriate character on your keyboard and then press the appropriate number from the pop-up.)

/* Hybrid map view */
"Hybrid" = "Hybrid" "Híbrido";

/* Satellite map view */
"Satellite" = "Satellite" "Satélite";

/* Standard map view */
"Standard" = "Standard" "Estándar";

Build and run the application again. Now all these strings, including the titles in the segmented control, will appear in Spanish (Figure 7.18). If they do not, you might need to delete the application, clean your project, and rebuild. (Or check your scheme language setting.)

Figure 7.18  Spanish MapViewController

Screenshot of the Map app (the Map View Controller) in iOS using Spanish language interface.

Internationalization and localization are very important for your app to reach the largest audience. Additionally, as you saw early in this chapter, your app might not work for some users if you have not properly internationalized it. You will internationalize (but not localize) your projects in the rest of this book.

Over the past five chapters, you have built a rather impressive application that allows the user to convert between Celsius and Fahrenheit as well as display a map in a few different ways. Not only does this application scale well on all iPhone screen sizes, but it is also localized into another language. Congratulations!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset