📜 ⬆️ ⬇️

Frequently asked questions about the WatchKit framework

For developers, Apple Watch is not just a sensational gadget. Now they have to learn the Watch Kit in order to create and adapt their applications for smart watches. As you explore this technology, of course, many questions arise.

We at Alconost have translated the extensive WatchKit FAQ. We will be glad if the work of our technical translators will be useful for you. For some questions, there are no clear solutions yet: in such cases, you should rely on common sense, expert advice and reasonable assumptions. This technology is still largely under development, and therefore subject to change. However, the answers to many burning questions have already been found. We invite you under the cat!



Main questions


What is WatchKit and how does it work?


WatchKit is Apple's framework for creating hybrid applications for Apple Watch watches, which includes Xcode 6.2.
')
WatchKit divides the app into two parts:



It is noteworthy that such an exchange of information between the Apple Watch and the iPhone takes place automatically and imperceptibly.

You work as usual, and WatchKit handles all data communication wirelessly. As for the code you write, your view and outlet are connected locally, even though they are located on a separate device. Very comfortably!


Can I develop applications for Apple Watch in Swift?


Yes, Apple Watch applications can be developed both in Objective-C and Swift languages ​​( translator's note: by the way, we translated part of the documentation on this language in Alconost ), and you can use two languages ​​at once. As an example, Apple has published two projects for the WatchKit environment:

In addition, the WatchKit Handbook, the WatchKit Video Practice Series and the WatchKit Training Materials book are written exclusively in Swift.

Apple provides the WatchKit framework documentation in Objective-C and Swift.


Can I create my own dials for watches?


No, custom dials for watches are not yet supported.

Changing the dials for hours is not yet supported!

How many hours of Apple Watch can I connect to one iPhone?


The connection is exclusive, so only one Apple Watch can be connected to one iPhone at a time.

Can I connect an Apple Watch to an iPad?


Not. Now Apple Watch can only be connected to the iPhone.

Can an app on an iPhone smartphone “wake up” its WatchKit extension and app in hours?


Not. The WatchKit extension can only request the system to launch a companion application for the iPhone, and it will do so in the background. Now work in the opposite direction is not supported.

Can third-party apps make phone calls from a clock app?


Not. There is no open API that allows you to initiate a phone call directly from the WatchKit extension. Since the companion iPhone application also cannot be put on a priority level, the system ignores all phone calls or openURL requests : from the companion smartphone application.

Can I access the pulse sensor and other clocks from a clock application?


Not. There is no software interface for accessing hardware sensors on the Apple Watch.

What is the difference between short, long, static and dynamic notifications?



- static notification contains a single text string, which is automatically filled in using the notification content. You can create a scene for a static notification in the application storyboard for hours, but in terms of customization, you can only change the color of the dividing line and title;
- dynamic notification requires subclassing WKUserNotificationInterfaceController . It is instantiated from the storyboard and allows you to define your own interface. Keep in mind that the dynamic notification interface is not always displayed. For example, if the battery of the watch dies, to save battery power, the system may decide to show a static notification interface instead of a dynamic one, since static notifications consume less energy.

Under the hood



Select the appropriate scheme

How to check the “quick view” view or notification using a simulator?


To run in the simulator for each "quick view" and notifications you need your own assembly scheme. Simply choose the appropriate scheme, collect and run.

Can the interface elements be placed one on top of another?


Not. By default, interface elements cannot be placed one on top of another. However, this restriction can be circumvented. For example, you can use the WKInterfaceGroup group and set a background image for what is a control, on top of which you want to add another. Then inside this group, you can add the necessary text lines, buttons, etc.

Can I customize the CALayer property of the interface elements?


Not. The Apple Watch interface elements do not have the CALayer property, since they do not originate from either the UIView class or the CALayer class.

Is it possible to subclass those classes that are in the WatchKit framework?


Nothing prevents subclassing any class in the WatchKit framework, but it may happen that you cannot use this feature. You can subclass some classes, such as WKInterfaceController and WKUserNotificationInterfaceController , and use them in the storyboard.

However, the storyboard clock application does not allow to change the class of interface elements. You cannot dynamically create interface elements and insert or delete them as displayed sub-elements; you can only hide or show those interface elements that already exist in the storyboard.

Is it possible to combine the interface controllers based on the page and based on the movement?


It is possible, but with some restrictions.

If you have a hierarchical interface , then the page-based interface can be represented using modules. If any of the pages is a hierarchical interface, then its root directory is displayed, and nothing will be added to its stack.

If you have a page- based interface, a hierarchical interface can be represented using modules, but only the root interface controller will be displayed, and adding to its stack will not work.

Does Apple Watch have equivalents for the UIActivityIndicator and UIAlertController classes?


No, but instead of the UIAlertController class, you can modally display a custom WKInterfaceController .

The action indicator can be bypassed by adding a sequence of images to create the necessary animation, or simply display a text string with the corresponding text. How this is done can be seen in the example of the Lister application provided by Apple: in the “quick glance” mode, one circular animation of the clock application represents 360 images!


Can I use Core Graphics to create images dynamically, and then use them in a clock application? Can they be cached on the clock?


Yes, it is possible, but any images using Core Graphics should be compiled on the iPhone as part of the expansion. Once the Core Graphics graphics context has been transferred to an instance of the UIImage class, it can be placed on the clock using the addCachedImage (_: name :) method from the WKInterfaceDevice class.

Can I use custom views in Apple Watch watches and customize interface elements outside of the open clock API?


Not. Custom views cannot be used. WatchKit supports only some of its own interface elements. These elements cannot be subclassed or customized outside their open API. There are the following interface elements: WKInterfaceLabel , WKInterfaceButton , WKInterfaceImage , WKInterfaceGroup , WKInterfaceSeparator , WKInterfaceTable , WKInterfaceSwitch , WKInterfaceMap , WKInterfaceSlider and WKInterfaceTimer .

How does an Apple Watch exchange information with an iPhone?


The Apple Watch is best used by Bluetooth LE and Wi-Fi to share information with a connected iPhone. The implementation of such information exchange is not transparent to either users or developers.


Can Apple Watch be used offline?


Yes. After activating the offline mode, you can turn on Bluetooth and Wi-Fi to share data and use the clock.


Turn on Wi-Fi and Bluetooth after activating offline mode

What happens to the app when the Apple Watch cannot communicate with the associated iPhone?


Simply put, the application will not work, and if it already works, then the work will be suspended.

In the WatchKit extension, the didDeactivate () method will be called on the current interface controller, and the necessary cleanup can be done. The red icon of the iPhone device will be displayed in the status line of the watch, indicating a loss of communication, and the interface will remain on the screen, but will not be interactive. Users can either reconnect or exit the application.

How does a clock app communicate with a companion app on an iPhone?


This is done in different ways. The most common way is when a watch app writes or updates data in a shared container, and then notifies the app on a smartphone. After that, the application on the smartphone can retrieve the changes from the shared container.

Another way is to transfer the data to the iPhone's application through the dictionary, but this method can only be initiated by the clock application. To do this, there is a separate API in the WatchKit extension: the openParentApplication method (userInfo: reply :) of the WKInterfaceController class is called , as shown in the following example:
// Notify companion iPhone app of some changes in the shared container. let kSharedContainerDidUpdate = "com.rayWenderlich.shared-container.didUpdate" let requestInfo: [NSObject: AnyObject] = [kSharedContainerDidUpdate: true] WKInterfaceController.openParentApplication(requestInfo) { (replyInfo: [NSObject : AnyObject]!, error: NSError!) -> Void in // Handle the reply from the companion iPhone app... } 

In the userInfo dictionary , you simply transfer the label or some data for the accompanying iPhone application with which you want to perform actions. To receive such a message, the accompanying iPhone application must execute the application (_: handleWatchKitExtensionRequest: reply :) in its application delegate:
 func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) { let kSharedContainerDidUpdate = "com.rayWenderlich.shared-container.didUpdate" if let isUpdate = userInfo[kSharedContainerDidUpdate] as? Bool { // Process request, then call reply block reply(...) } } 

If the associated smartphone application is paused or stopped, the system will launch it in the background. Depending on the purpose of the message, the accompanying iPhone application may output something in the response block, which the clock application can then process accordingly.

How does the iPhone app communicate with the watch app?


An application on an iPhone device cannot initiate the exchange of information with its extension. In addition to recording to a shared container or responding to requests from a watch app, an application on a smartphone can use the Darwin Notification Center notification center to notify the WatchKit extension about a specific event. The Darwin Notification Center Notification Center is the Core Foundation API.

When using the Darwin Notification Center, you need to remember some very important points:


What happens if you do not use static or dynamic notification interfaces?


Even if there is no associated watch application for the application on the iPhone, the system will display a notification on the watch for that application. However, the interface for notifications by default does not have a custom design. If the application has interactive notifications, the system will hide these actions on the clock.

What is the difference between setImage (_ :) and setImageNamed (_ :)?


The setImageNamed (_ :) method is used when the image to be displayed is either stored in the clock cache, or is in the asset directory of the watch application kit, and setImage (_ :) should be used when the image is not stored in the cache — so the image data will be transmitted to the Apple Watch wirelessly.

The image is stored in the clock cache if it meets one of the following criteria:
  1. In the project, the image is related to the purpose of the application for the clock, that is, the image is located in the assets catalog related to the purpose of the watch application in the project.
  2. The image was directly cached in advance using one of the following WKInterfaceDevice APIs : addCachedImage (_: name :) or addCachedImageWithData (_: name :) .


Can iCloud be used in an app for a watch?


Yes, you can use iCloud in the Apple Watch app. How to do this, you can see the example of the application-assistant Lister - one of the simple projects published by Apple.

Animation


How to add animation to the application for hours?


The only way to display an animation on an Apple Watch is image sequence . To create an animation, you must create a series of images in advance, and then loop through them, as in a cartoon drawn in a notebook. Times of animated gifs are back! ;]

To create your own animation, you can display a sequence of static images in a WKInterfaceImage object.
 @IBOutlet weak var image: WKInterfaceImage? ... image?.setImageNamed(image1) // Load the initial image using the required <name><number> format image?.startAnimating() // Starts animating ... image?.stopAnimating() // Optional. Stops animating. 

You can also animate only a portion of the collection of images, as shown in the following code snippet:
 image?.startAnimatingWithImagesInRange(range, duration: 2, repeatCount: 1) 

Can I create animations for Apple Watch as a code?


Yes - but perhaps not in the way you think. As stated above, there is no Core Animation framework or equivalent. You can use Core Graphics to provide each frame with an offscreen context animation, assign it to a UIImage instance, and in the end, you will get a series of images that can be animated on an Apple Watch.

The following code snippets show how to create an animation for a moving circle using the Core Graphics framework by generating a sequence of images for each frame (code courtesy of Jack Wu, one of the authors of the WatchKit Tutorial ):
 // Create an offscreen context UIGraphicsBeginImageContextWithOptions(size, opaque, scale) let context = UIGraphicsGetCurrentContext() for centerX in 0..100 { // Draw a circle at centerX. // Create a snapshot. let image = UIGraphicsGetImageFromCurrentImageContext() // Write the image as a file let data = UIImagePNGRepresentation(image) let file = "path\\image_\(centerX).png" data.writeToFile(file, atomically: true) } // End the context. UIGraphicsEndImageContext() 



What is the maximum frame rate on an Apple Watch?


You cannot set the frame rate on an Apple Watch. However, you can set the duration of the animation, and the system will automatically determine the frame rate.

If a sequence of images is sent over the wireless channel — for example, when images are not cached — they will run at up to 10 frames per second. If the images are already cached on the Apple Watch through the image cache or the asset catalog in the WatchKit application bundle, they will run at up to 30 frames per second.

Debugging and unit testing


How to launch and debug an iPhone app at the same time as an Apple Watch app using simulators?


  1. Build and run the clock application - the Apple Watch simulator will start and the clock application will bind to the debugger.
  2. Then, in the iOS simulator, launch the application for the smartphone by tapping its icon.
  3. Now go back to Xcode and in the top menu, click Debug \ Attach To Process , then select the appropriate application for the iPhone — this will add a new process to the Xcode debugging browser, and attach the smartphone application to the debugger.


How to conduct unit testing extension WatchKit?


The unit tests for the clock application are created in the same way as the unit tests of the applications for the iPhone and iPad: it is enough to add a new unit test goal to the project to extend WatchKit. However, specifying the application for the clock as a host application will fail.


For the purpose of the iPhone application, the smartphone application itself is displayed as a host application.


And for the WatchKit extension, there is no host application

The goal of the unit testing of the WatchKit extension is to separately add each file that needs to be tested.


From the WatchKit extension to the unit test target, add the files you want to test.

Data sharing


How to organize data sharing between the WatchKit extension and the corresponding iOS application?


To do this, you need to activate the App Groups application group - a container in the local file system that can be accessed by the extension and its application for the iPhone device. You can define several groups of applications and activate them for different extensions.

After activating application groups, you can use any suitable method from the following:

 let kMyAppGroupName = "com.raywenderlich.mywatchapp.container" var sharedContainerURL: NSURL? = NSFileManager.defaultManager(). containerURLForSecurityApplicationGroupIdentifier(kMyAppGroupName) 


 let kMyAppGroupName = "com.raywenderlich.mywatchapp.container" let sharedUserDefaults = NSUserDefaults(suiteName: kMyAppGroupName) 

Note. In order to avoid data corruption, it is necessary to read and write data in a shared container consistently, since different processes can simultaneously access a shared container. NSFilePresenter and NSFileCoordinator are recommended for consistency between reading and writing. It is not recommended to use the file reconciliation API in the extension of the application, as this may cause a hang.

The reason for this behavior is the life cycle of the application extensions. Application extensions have only 3 states: a) executed, b) suspended and c) completed. If the work of the extension of the application that uses the file matching API is suspended while writing, such a process will not have the opportunity to free the resource, and other processes will be blocked.

When an application for an iPhone or iPad device is moved to the background, it receives a notification through its application delegate, and then must remove the presenter objects. When the application is brought back to the fore, these presenters can be added again.

Instead, you can use an atomic safe save operation, for example, writeToURL (_: atomically :) in the NSData class. SQLite and Core Data also allow you to safely exchange data in a shared container between different processes, even if one of them is suspended at the time of the operation.

For more information, see Technical Note TN2408. Access to shared data from the extension and the application containing it. "

How to share a Core Data database between a clock app and an iPhone app?


To share a file from Core Data persistent storage, you need the same mechanism as shown in the data sharing example. Below is a snippet of code that demonstrates how the mechanism works:
 let kMyAppGroupName = "com.raywenderlich.mywatchapp.container" var sharedContainerURL: NSURL? = NSFileManager.defaultManager(). containerURLForSecurityApplicationGroupIdentifier(kMyAppGroupName) if let sharedContainerURL = sharedContainerURL { let storeURL = sharedContainerURL.URLByAppendingPathComponent("MyCoreData.sqlite") var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) coordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: nil) } 


Getting down to business


Can I make games for Apple Watch? What games are suitable?


Although it is too early to talk about what kinds of games will be successful and whether users will want to play games on the clock, but almost with full confidence we can say that the Apple Watch should be viewed in a different light.

Developing games on iPhones and iPads required a completely different way of thinking than playing games on a desktop computer. The Apple Watch also needs a special approach.

We already know about the limitations of the platform: Apple Watch has no API for hardware access, they do not support gesture recognition and do not allow drawing on the screen. Remember: you can only use your own interface elements.

But do not allow these restrictions to stop the flight of creative thought - consider them to be fundamental principles. :]

How to make money with Apple Watch apps?


It's too early to talk about it. One thing to be borne in mind: the iAd platform is not supported, and given the small screen size and time during which the user will interact with the application for the clock, on-screen advertising will likely annoy users and in any case will not be so effective as to justify financial costs of it.

In addition, if the WatchKit extension is included in the application bundle, it cannot be deactivated or otherwise prevented the user from installing it. Therefore, it can not be made a paid addition, which can be purchased from the application.

However, there are still ways to monetize WatchKit extensions:

This, of course, is not an exhaustive list of the monetization capabilities of WatchKit applications, but one thing is clear: the monetization should be approached as creatively as the watch applications themselves.

Is there any reason to believe that apps for watches are a new way to make a living through developing apps for the App Store?


Any conclusions do prematurely. And although the Apple Watch is really a completely new platform, full of interesting features, with its appearance the “gold rush” that could be observed when opening the App Store will not start.

It must be borne in mind that the Apple Watch has a different purpose. Given their appearance and price, they are closer to the decoration that communicates with the iPhone, than to an independent device.

However, the WatchKit extension can help a particular application stand out from the crowd. As applications developed specifically for tablets iPad enjoyed greater success than applications for smartphones iPhone, just fit for iPad, and a well-designed application for watches Apple Watch, which complements any application for iPhone, can increase sales.

And what are your predictions about the Watch Kit?


About the translator

The article is translated in Alconost.

Alconost is engaged in the localization of applications, games and websites in 60 languages. Language translators, linguistic testing, cloud platform with API, continuous localization, 24/7 project managers, any formats of string resources.

We also make advertising and training videos - for websites selling, image, advertising, training, teasers, expliners, trailers for Google Play and the App Store.

Read more: https://alconost.com

Source: https://habr.com/ru/post/257023/


All Articles