For the More Curious: The Application Bundle

When you build an iOS application project in Xcode, you create an application bundle. The application bundle contains the application executable and any resources you have bundled with your application. Resources are things like storyboard files, images, and audio files – any files that will be used at runtime. When you add a resource file to a project, Xcode is smart enough to realize that it should be bundled with your application.

How can you tell which files are being bundled with your application? Select the Homepwner project from the project navigator. Check out the Build Phases pane in the Homepwner target. Everything under Copy Bundle Resources will be added to the application bundle when it is built.

Each item in the Homepwner target group is one of the phases that occurs when you build a project. The Copy Bundle Resources phase is where all of the resources in your project get copied into the application bundle.

You can check out what an application bundle looks like on the filesystem after you install an application on the simulator. Print the application bundle path to the console and then navigate to that directory.

print(Bundle.main.bundlePath)

Control-click the application bundle and choose Show Package Contents from the contextual menu (Figure 16.9).

Figure 16.9  Viewing an application bundle

Screenshot shows an application bundle in Xcode.

A Finder window will appear showing you the contents of the application bundle (Figure 16.10). When users download your application from the App Store, these files are copied to their devices.

Figure 16.10  The application bundle

Screenshot of an application bundle is shown.

You can load files from the application’s bundle at runtime. To get the full URL for files in the application bundle, you need to get a reference to the application bundle and then ask it for the URL of a resource.

// Get a reference to the application bundle
let applicationBundle = Bundle.main

// Ask for the URL to a resource named myImage.png in the bundle
if let url = applicationBundle.url(forResource: "myImage", ofType: "png") {
    // Do something with URL
}

If you ask for the URL to a file that is not in the application’s bundle, this method will return nil. If the file does exist, then the full URL is returned, and you can use this URL to load the file with the appropriate class.

Bear in mind that files within the application bundle are read-only. You cannot modify them, nor can you dynamically add files to the application bundle at runtime. Files in the application bundle are typically things like button images, interface sound effects, or the initial state of a database you ship with your application. You will use this method in later chapters to load these types of resources at runtime.

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

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