Sharing Data in Apple Watch Applications
- Creating a Shared App Group
- Creating the iOS Application
- Coding the Apple Watch App
- Using a Framework to Contain Repetitive Code
In my previous articles on Apple Watch programming, you learned about the basics of Apple Watch programming and how your watch apps rely on the extension running on your iPhone. As the Apple Watch application is an extension of your iOS app, your watch apps and iOS need to share data constantly. For example, suppose you are writing a weather application. Your iOS app allows users to select a country to find out about its weather. In addition, you want to let users check the weather by using their Apple Watch. In this case, it is important for both apps to be able to access the same set of data.
In this article, you will learn how to share data between the iOS and watch apps, and how to architect your apps to facilitate code reuse.
Creating a Shared App Group
In order to share data between the watch app and the containing iOS app, you need to create a shared container known as the shared app group. Follow these steps:
- Using Xcode, create a Single View Application and name it SharingData.
- Add a WatchKit App target to the project.
Select the project name in Xcode and then the SharingData target, and select the Capabilities tab (see Figure 1). Turn on the App Groups section.
Figure 1 Turning on the App Groups feature of your project.
When prompted, enter your Apple ID account that is enrolled in the iOS Developer Program. Once your account is authenticated, select its Apple ID and click Choose (see Figure 2).
Figure 2 Selecting an account for enabling App Groups.
Click on the plus (+) button under the App Groups section and enter a name to use for the shared container. I entered the container name shown in Figure 3:
Enter the unique name for your group and click OK.
Figure 3 Entering a name for the shared app group.
Your group name should now appear in the App Groups list (see Figure 4). If you encounter a problem in registering the name, make sure that you have a valid provisioning profile on your Mac. Then click the Refresh button to try again.
Figure 4 The shared app group added to the project.
Repeat the previous steps for the SharingData WatchKit Extension target (see Figure 5). This time, you just need to select the shared group name that you entered earlier.
Figure 5 Adding the shared app group as a WatchKit extension target.