LoginSignup
32
31

More than 5 years have passed since last update.

Apple Watchでカウントダウンアプリを作る

Last updated at Posted at 2014-12-25

この投稿は Apple Watch Advent Calendar 2014 の 25日目の記事です。

はじめに

Apple Watchでタイマーを使う用途は多いと思います。
例えば大晦日のカウントダウンとか、滅びの呪文を唱えるシーンとか、マラソンストップウォッチとか・・・まあ色々。

そんなわけでApple Watch向けのカウントダウンアプリを作るためのチュートリアルを作成しました。

未公開情報等もありますので、プロジェクトやスクリーンショットの公開は控えます。手順で説明したいと思います。

作成するもの

Apple Watch上でボタンを押すとカウントダウンが始まり、カウントダウンが終了すると文字が出現するアプリを作成します。

実装手順

  1. Xcode 6.2beta版を用意

  2. 新規プロジェクトを作成します(iOS -> Application -> Single View Application)
    説明のため名前はSampleとします(何でもOKです)

    補足

    Apple WatchはiPhoneアプリと連携する形でしか起動できません。
    よってWatchKitのプロジェクトも単体では作成できず、iPhone向けのアプリを土台として作成する必要があります。

  3. 上部メニューのFile -> New -> Target -> iOS -> Apple Watch -> Watch AppからWatchKitプロジェクトを追加します。
    チェック等設定はデフォルトの状態とします。

  4. Sample Watch App/Interface.storyboardを選択
    Interface Controller Sceneに

    • Timer
    • Button
    • Label をそれぞれ配置します。
  5. storyboardを開いた状態で、Sample WatchKit Extension/InterfaceController.swiftを開きます。(optionを押しながら選択)
    storyboard上のTimer, Button, Labelそれぞれについて、右メニューの一番右のタブからソースコードにリファレンスを張ります。(controlを押しながらInterfaceController.swiftのソースコード上にドラッグ)

    補足

    Timer, Labelは項目が初期状態で1つしか無い筈です。
    Buttonは項目が複数ありますが、"Sent Actions"からリファレンスを張ります。
    Buttonのテキストを適当に設定します。今回は"Timer Start"としました。

  6. 次にTimerのスタイルの設定をします。
    storyboardからTimerを選択し、右メニューの右から2番目のタブを開きます
    FormatのセレクトボックスではTimerの時間表示形式を選択できます。
    今回はShortを選択します

    Enabledにはチェックを入れません。簡単に説明すると、ここにチェックを入れるとソースコード上で何も書かなくてもtimerが開始します。

    storyboard上での設定は以上です。

  7. 次にInterfaceController.swiftを編集します。

import WatchKit
import Foundation


class InterfaceController: WKInterfaceController {
    @IBOutlet weak var timerUI: WKInterfaceTimer!
    var timer: NSTimer!
    let timerDuration: NSTimeInterval = 10
    @IBOutlet weak var label: WKInterfaceLabel!

    override init(context: AnyObject?) {
        // Initialize variables here.
        super.init(context: context)

        // Configure interface objects here.
        NSLog("%@ init", self)
    }

    func timerFinished() {
        NSLog("Go!")
        label.setText("Go!")
        label.setTextColor(UIColor.greenColor())

        // Configure any actions after timer finished
    }

    @IBAction func timerStart() {
        NSLog("Ready...")
        // Set label
        label.setText("Ready...")
        label.setTextColor(UIColor.redColor())

        // Set timer interface
        timerUI.setTextColor(UIColor.redColor())
        timerUI.setDate(NSDate().dateByAddingTimeInterval(10))
        timerUI.start()

        // Set system timer
        timer = NSTimer.scheduledTimerWithTimeInterval(timerDuration, target: self, selector: Selector("timerFinished"), userInfo: nil, repeats: false)
    }


    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
        NSLog("%@ will activate", self)
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        NSLog("%@ did deactivate", self)
        super.didDeactivate()
    }

}

これで完了です。

補足

WKInterfaceTimerには、timerが終了したときのイベントを設定することが出来ません。
画面上に表示するtimerとは別にシステム内部で管理するようのtimerを用意して、同期させる必要があります。
今回は、NSTimerとWKInterfaceTimerを同時にstartさせ、同時にstopさせるようにしています。

Simulator上での実行

  1. Xcodeの左上からSimulatorを選択します。
    Sample Watch App -> iOS Simulator -> iPhone6を選択 (Sample -> iOS Simulator -> iPhone6では無いので注意!)
  2. Command + RでRunします。
    Apple WatchのSimulatorが起動してlabelなどが表示されればOK
  3. Apple Watch Simulatorで"Timer Start"ボタンを押下します
    Apple Watch上でTimerが始まり、コンソールログで"Ready..."と出ます。 Timerが終了すると、コンソールログで"Go!"と表示されます。

応用

InterfaceController.swift内のtimerFinished関数内に、カウントダウンが終了したときの処理を記述すればいろいろな用途に使えます。遊んでみてください。

参考

32
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
31