"Go" using Swift to develop WatchKit Getting started tutorial

Source: Internet
Author: User
Tags class definition

Start learning watchkit!

Updated on January 19, 2015: Tested by the Xcode 6.2 beta release; No project/code changes required. Remember to use the latest beta version of Apple!

iOS developers rejoice-WatchKit is finally here!

WatchKit is a development package for the new framework and related technologies for creating Apple Watch applications that Apple is accompanying with the Xcode 6.2 beta release.

In this WatchKit tutorial, you will use Swift to create your first WatchKit application. Specifically, you will develop a bitcoin price tracking application and create a Watch application that is used with it.

In this process, you will learn how to architect WatchKit applications, how to make some new WatchKit-specific UI controls work, WatchKit layouts, and so on.

Let's get started! ┗ (°0°) ┛

Note: Since the Apple Watch SDK documentation is open to the public, we have not heard any conflicting provisions, and we assume that it is appropriate to chat WatchKit now. If anyone hears the official news about it, please let us know!

Entry

First, download the starter project for this WatchKit tutorial:

Http://cdn2.raywenderlich.com/wp-content/uploads/2014/11/BitWatch-Starter.zip

Open the Starter project and select the iphone 6 emulator as the running target. Build and run your application to feel it. The app uses the bitcoin average price index API to get the latest Bitcoin price and display it on the screen.

Are you a bitcoin billionaire?

Now it's time to start tracking your Bitcoin wealth on watch!

In Xcode, navigate to File\new\target ... and select the Ios\apple watch\watch app template.

A watch app can be bundled with the main iOS and work like an extension. However, this option will create a separate target. Click Next to continue.

In the following screen, Xcode will automatically populate a number of values, some of which cannot be changed, such as the product name.

Make sure the language is set to swift and that the include Notification scene and include Glance scene options are not selected. Click on the finish,xcode to set the target and some of the watch interface's basic template files, ready for your development!

If you look at the Project Navigator, you will see that there are two different groupings:

Watch Group

    1. The Watch application group contains just storyboard and image assets ... And no Code! Can be thought of as the "view" of your application.

    2. The WatchKit extension contains event code that executes in events such as application startup, button taps, or switch changes. You can think of this as the "Controller and model" of your application.

Watchkit_03

Until we have access to the "Native" watch app, it's a good idea to think of this setting as: Watch is the second smaller screen from the extended control. In fact, the simulator puts watch just as an external monitor and can see the start of adding and testing the interface object.

Note: The terms of the watch application are slightly different from iOS and Mac applications, not views, controllers, and view controllers, but interfaces, interface objects, and interface controllers.

Watch interface

When designing your Watch application interface, you can use storyboard and interface Builder, just like your iOS app. Look here, open the Bitwatch Watch application group and select Interface.storyboard.

Watch Storyboard1

You will see an empty interface controller in the storyboard. Let's add some controls!

Start dragging the label from the object library to the interface. Then, under it, a button is delegated.

Watch Storyboard2

You may notice some strange places here-you can drag the interface elements around the storyboard, but only vertically (not horizontally) to change your position and lock the control vertically one by one.

In other words, you can put the tag on the button or put the button on the label, but you can't, like you can "casually" drag the element on iOS. Accustomed to using automatic layout in iOS you might make the following expression:

Confusedguy

Originally, there was no automatic layout on Apple Watch, and it had its own mechanism for layout and positioning. Let's take a look.

Positioning

This is not much like automatic layout, but in your watch application, every interface element must be "pinned" to something, whether it's the edge of the screen or other objects. This will determine its final position.

By default, two objects are positioned at the top; You can change their order so that one of them is on top of the other, but their positions will be placed relative to the top of the screen.

You can use the Attributes Inspector in the Utilities panel to adjust the position of the interface elements. Select the label and change its horizontal position property to center, so that the vertical position property is top.

Watch Center Top

Next, select the button, change its horizontal position property to center, and its vertical position property is bottom.

Watch Storyboard3

If you describe it in automatic layout terms, you can think of it as pinning the interface elements to the top and bottom of the layout. Since watch's screen is so small, it's simple enough to just select two positions to adjust-horizontal and vertical. You'll see how easy it is to position yourself relative to each other. In the back, you can add more things to the interface.

Formatting

First, let's set some text and format to use the interface to look nice, and explore some other options for use in Attributes Inspector.

Select the label and make sure that the attributes inspector in utilities is turned on. The label will display the price of Bitcoin, so set the text to $0.00 and select center alignment. Open the font pop-up block by clicking the "T" icon in the Font field, and set the value to custom, Avenir Next, Demi Bold, size 30.

Watch Label Font

Select the button and change its title to refresh. Change its font to custom, Avenir Next, Medium, size 16.

Watch button

This looks great!

Watch Storyboard4

Note that you can change properties such as text, title, and color at run time through code, but you can only modify the font and positioning properties in the storyboard. So, if you're used to setting your layout in code. Developing Watch applications requires you to spend a little more time on interface builder than developing IOS apps.

Note: Another friendly reminder that WatchKit is beta status-so it's possible that Apple will be able to open up more methods and properties of the interface object in the code sometime in the future.

Action and Outlet

Action and outlet work as you would expect, allowing you to access interface elements and manipulate user actions, such as keystrokes, from your code.

If you're in trouble, it's a bit odd to associate these things because the storyboard is in watch App target, and the code is in WatchKit Extension target.

How can I associate action and outlet across target? Can even be connected across devices? Because the app is on watch, and it expands on the phone!

Fortunately, this magical part of Apple is being processed in the background, so you don't have to worry about it.

Remote action and outlet? Bluetooth Magic!

Behind the scenes, Apple is responsible for all the wireless communication between your WatchKit app and iPhone watchkit extension, using Bluetooth technology. It's cool, isn't it?

Open the Assistant editor and make sure that Interfacecontroller.swift is turned on. Hold down the CTRL key, drag from the price tag into the Interfacecontroller class, define create a outlet, call it Pricelabel, and click Connect.

Watch Outlet

Next, hold down CTRL and drag from the button into the class. This time, be sure to select action to create a method, not a outlet. Name the action method refreshtapped, and then click Connect.

This is the interface so far. Now it's time to switch to the code and get some data to show up!

Basic WatchKit Code

The starter project includes a framework called Bitwatchkit that contains some custom code to get the price of Bitcoin. We have this code in the framework so it can be used in the iphone app at the same time and can be easily used in iphone WatchKit extensions.

Add the framework to your extension, open the project file in the Navigator, and select the target for the Bitwatch watchkit extension. Select the General tab, and then scroll down to the linked frameworks and Libraries section.

Watch extension

Click the + button under the Frames list. You will see a window listing the frames you can use to add, and you should see bitwatchkit.framework at the top of the list. Select it, and then click Add.

Watch frame

Now that the framework has been added, you can update your watch interface with some real data!

Switch to Interfacecontroller.swift's WatchKit extension group. Add the following import statement to the top of the file:

Import Bitwatchkit

This will allow you to access the tracker class defined in the framework.

Next, add the following properties to the class definition:

Let Tracker = Tracker ()
var updating =false

You need to use tracker instances to get Bitcoin prices over the network. You will use updating to identify whether there is a pending "Update price" request.

Add the following helper methods to the class:

Private func Updateprice (price:nsnumber) {
  Pricelabel.settext (Tracker.priceFormatter.stringFromNumber (Price))
}

This method requires a NSNumber value to update the label on Watch. Tracker also includes a handy number format that will use some numbers like 93.1 to convert to a string, such as "$93.10".

Add an auxiliary method to the class:

Private func update () {  
1   
if!updating {
Updating =true    
2     
Let OriginalPrice = Tracker.cachedprice ()  
   3   
  Tracker.requestprice {(price, error)-in      
4      
If error ==nil{      
   Self.updateprice (price!)      
}      
Self.updating =false
    }
  }
}

Let's take a step-by-step look at:

1. Run a quick check to make sure you are not in the update.

2, cache the current price, so only need to change the price in the update UI interface.

3, Requestprice () is the method on the tracker, through the network request to obtain the latest Bitcoin price. Once completed, it executes a closure.

4. If the request succeeds, all you need to do is call Updateprice () to update the label.

Now, you just need to call these methods from somewhere to get the real data, which is displayed on the interface.

Interface life cycle

Your first chance is to set up your interface elements in Awakewithcontext (_:), at which point the entire interface is loaded and the action and outlet are connected.

This means that you can set the interface object and start displaying the data. However, so far the interface is not necessarily put on watch! Because it is important to make things a reasonable state: you may not want expensive operations, such as making network calls.

Add the following to the end of the Awakewithcontext:

Updateprice (Tracker.cachedprice ())

This updates the price tag with the previous cached value, if one exists. Because this value is cached by the tracker, it is local data and is very expensive to obtain.

The following is added to the tail of willactivate ()

Update ()

Willactivate is like the viewwillappear in iOS. And that means the interface is about to activate and appear in watch. This is a good signal to refresh the data, so call Update () here to start the network request and update the label.

Finally, add the same line of code to the refreshtapped:

Update ()

When the user clicks Refresh, you want the same thing to happen: Call Update () and display some new data.

Test your application

To test your watch application, you need to have watch as an external monitor. If your iphone simulator has an app running, switch to it. Otherwise, build and run the application, stop it in Xcode, and then switch back to the iOS emulator. In the menu, navigate to Hardware\external displays and select an Apple Watch option.


Watch simulator

You should now have two simulator Windows-one showing the iphone and one for watch.

Go back to Xcode, select the Bitwatch Watch App in the toolbar, and select iphone 6 simulator.

Watch scheme

Build and run, and then switch to the emulator. You should see Bitcoin's data in Apple Watch!

Watch APP1

More interfaces

Now that you're getting started, here's a look at more things you can do with the interface.

In this application, there are also two elements that you want to implement on watch:

    • Last Update time

    • Upward/outward image to show whether the price increases or decreases

To do this, you first need to add the image to the asset directory. Open the images.xcassets of the Bitwatch Watch app group. Be careful here: there are 3 images.xcassets files in the project, so make sure you're in the right group!

The starter project consists of two image files: [email protected] and [email protected]. From the Finder window, drag these two files into the image collection list.

See Asset

Note that the unique @2x variant of the image is also included. You only need @2x images in WatchKit – because there is no Apple watch! with a non-retina screen

Next, open Interface.storyboard again and return to the layout.

Drag another tab to the interface and put it on the Reresh button. Set the label text to last Updated, and set the font to custom, Avenir Next, Regular, and size 13. Also change the text alignment to center.

For positioning settings, change the horizontal Location property to center and the vertical location property to bottom.

Watch Storyboard5

You might think: If the refresh button, the positioning property of the new tab is set to the bottom, watch knows how, in what order to place them?

On iOS, in the document outline, the view order determines the Z-order, or determines which view is "at the top" or "behind" another view. For the Watch interface, the interface elements do not overlap, so there is no need to track z-order. Instead, the order in the document summary reflects the vertical order from top to bottom (combined with vertical alignment settings).

Watch appearance

To understand what I mean, swap the order of the refresh and last updated controls in the outline-you'll see them visually exchanged in Interface builder. When you're done, change back.

Group

So far, your watch interface has included interface objects stacked on top of each other. So, how do we do it all by side?

Another object for you to use is a group. Groups are like containers, and you can put the interface objects inside them. However, they also have settings for whether the elements they contain should be arranged horizontally or vertically. You can get a variety of different interface placement by nesting groups in groups and using different layouts!

Note: A group can be an interface element that has a background color and a picture. In this application, in addition to how they contribute to the layout, is not visible to the user (translator note: Because the group in this app, there is no background color and picture, so not viewable)!

Below are the indicators that look like the price rise/fall in the iphone app:

Watch app cut head

So, the master plan is to place a picture next to the label.

Drag a new group from the object library onto the storyboard and place it between the price label and the last updated label. In Attributes inspector, make sure that the group layout is set to horizontal.

Watch Storyboard6

Next, drag a picture control from the object library into the group control. Then drag a new label into the group and place it on the right side of the image.

Watch Storyboard7

This way, there are two objects that are side-by-side, but now the question is how to set their position and size.

Location and size

Select the label and change both its horizontal and vertical position properties to center. Do the same for the picture control.

Because the images and labels are within a group, they are centered in the group and not in the outer storyboard as a whole object. This means that groups move around and, for some reason, are resized, and the images and labels stay in the center of the group.

By default, most interface objects can have their size property set to the size to Fit Content. This works well for labels because the text may change. However, the arrow picture is in the resource bundle and has a known size that you can set in the storyboard. This means that watch will not need to calculate dimensions in the back.

Select the image and find the size section in Attributes Inspector. Change the width setting to fixed width and height to fixed height. Set the width and height values at the same time to 32.

Watch size

Integrated interface

If you just put the tag on the storyboard, the text of the label doesn't change. Change its text to 1BTC and modify its characters to: Custom, Avenir Next, Regular, and size 13.

This image will change based on the price of the previous Bitcoin (the translator notes: The previous price is lower or higher than the current price), so you need a outlet. Open the auxiliary editor and hold down the CTRL key to drag from the image into the class definition. Name the image outlet, and then click Connect.

For the "Last Updated" tab, you need another outlet. Hold down the CTRL key, drag from the label to the class definition, and name Lastupdatedlabel, and then click Connect.

This is all it has to do with the interface – before you start tracking your bitcoin assets. If you update the layout from your code, you need some more code and some tricks.

Integration Code

Open Interfacecontroller.swift. There are two new things to deal with: "lastupdated" tags and images.

Add the following helper methods to the class:

Private func updatedate (date:nsdate)
{  
Self.lastUpdatedLabel.setText ("Last Updated \ (Tracker.dateFormatter.stringFromDate (date)")
}

This method updates the last updated tag just like the price tag update. Similarly, tracker has a formatter object, in which case the date is formatted to show only the time.

Add an auxiliary method to the class:

Privatefunc updateimage (Originalprice:nsnumber, Newprice:nsnumber) {

If Originalprice.isequaltonumber (newprice) {

1

Image.sethidden (True)

} else {

2

If Newprice.doublevalue >originalprice.doublevalue {

Image.setimagenamed ("Up")

} else {

Image.setimagenamed ("Down")

}

Image.sethidden (False)

}

}

This method will compare the original price with the new price.

1. If both prices are the same, hide the arrow image.

2, if the two prices are different, according to the price changes, set the picture as "up" or "down", while unhide the image, make it visible again.

Calling Sethidden will cause the layout to reflow. Remember how to center the picture and the "1 BTC" tag in the group? When you hide the image, this will leave extra space on the left side of the label. However, the interface is smart enough to recalculate the layout and move the label so that the label remains centered within the group.

Note: You can hide things and use Setalpha to set the Alpha property of the interface object to 0, while still letting them "occupy space".

Now that the helper methods are in place, you need to call them.

The following lines are added to the tail of the Awakewithcontext:

Image.sethidden (True)

Updatedate (Tracker.cacheddate ())

Since you have no previous price information at startup, you have a hidden image at the beginning. The price comes from the cache, and of course you can fetch the date from the cache.

Next, locate update () and add the following line to the innermost if block. is the block with the IF error = = Nil {condition:

Self.updatedate (NSDate ())

Self.updateimage (OriginalPrice, newprice:price!)

This updates the last updated label to display the current time. Here, too, you get the previous price and the new price, and then if the price changes, you can use UpdateImage to display an image of the up or down arrows.

Build and run the monitoring application to see the simulator.

You should see the current price as shown before. Because you have already run the application once, you should already have a cache price, and if the cache price is different from the current price, you should see an up or down arrow.

The source data is updated every minute, so you can wait a minute and then click the Refresh button to get the latest Bitcoin price. Can you afford the Apple Watch version of solid gold? ]

How do I start here?

Here is the last example project of the WatchKit tutorial above. :

Http://cdn1.raywenderlich.com/wp-content/uploads/2014/11/BitWatch-Final-1.2.zip

Congratulations-you now know the basics of making WatchKit apps!

However, there is much more to learn-including additional interface objects, navigation, and switching passes (referred to as hand Off). And remember, this is just learning one type of application WatchKit-you can also make glances (similar to today's extension), or customize actionable push notifications.

Translator: Excellent network

Greg Heo

Original: http://www.raywenderlich.com/89562/watchkit-tutorial-with-swift-getting-started

"Go" using Swift to develop WatchKit Getting started tutorial

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.