For the More Curious: Bundle’s Role in Internationalization

The real work of taking advantage of localizations is done for you by the class Bundle. A bundle represents a location on the filesystem that groups the compiled code and resources together. The “main bundle” is another name for the application bundle, which contains all of the resources and the executable for the application. You will learn more about the application bundle in Chapter 16.

When an application is built, all of the lproj directories are copied into the main bundle. Figure 7.19 shows the main bundle for WorldTrotter (with some additional images added to the project).

Figure 7.19  Application bundle

Screenshot of the Application Bundle contents displayed on the Xcode, as directory hierarchies.

Bundle knows how to search through localization directories for every type of resource using the instance method url(forResource:withExtension:). When you want a path to a resource bundled with your application, you call this method on the main bundle. Here is an example using the resource file Boo.png:

let path = Bundle.main.url(forResource:"Boo", withExtension: "png")

When attempting to locate the resource, the bundle first checks to see whether the resource exists at the top level of the application bundle. If so, it returns the full URL to that file. If not, the bundle gets the device’s language and region settings and looks in the appropriate lproj directories to construct the URL. If it still does not find it, it looks within the Base.lproj directory. Finally, if no file is found, it returns nil.

In the application bundle shown in Figure 7.19, if the user’s language is set to Spanish, Bundle will find Boo.png at the top level, Tom.png in es.lproj, and Hat.png in Base.lproj.

When you add a new localization to your project, Xcode does not automatically remove the resources from the top-level directory. This is why you must delete and clean an application when you localize a file – otherwise, the previous unlocalized file will still be in the root level of the application bundle. Even though there are lproj folders in the application bundle, the bundle finds the top-level file first and returns its URL.

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

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