LoginSignup
4
2

More than 1 year has passed since last update.

AppleWatch の振動機能

Posted at

概要

AppleWatchの振動機能を使うアプリを作ってみようと思い
振動の機能を簡単に試してみた。

そしてAppleWatchの振動機能は Haptic(触覚) と呼ぶんですね

ソースコード

ContentView.swift
import SwiftUI

struct ContentView: View {

    let types:[String] = [
        "notification",
        "directionUp",
        "directionDown",
        "success",
        "failure",
        "retry",
        "start",
        "stop",
        "click",
    ]

    var body: some View {
        List{
            ForEach(0..<types.count) { idx in
                Button(types[idx]) {
                    knock(type: WKHapticType(rawValue: idx))
                }
            }
        }.listStyle(CarouselListStyle())
    }

    func knock(type: WKHapticType?) {
        guard let hType = type else { return }
        WKInterfaceDevice.current().play(hType)
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

解説

AppleWatchの画面に表示される種別名が書かれたボタンをタップすると対応する振動をします。

肝は WKInterfaceDevice.current().play(hType) だけですね。

play(..)メソッドの型はこんな感じ

    open func play(_ type: WKHapticType)

WKHapticType は、こんな感じみたいです。

WKInterfaceDevice.h
public enum WKHapticType : Int {

    case notification = 0
    case directionUp = 1
    case directionDown = 2
    case success = 3
    case failure = 4
    case retry = 5
    case start = 6
    case stop = 7
    case click = 8
    // The following types can only be used while the app has an active navigation session running:
    @available(watchOS 7.0, *)
    case navigationLeftTurn = 9
    @available(watchOS 7.0, *)
    case navigationRightTurn = 10
    @available(watchOS 7.0, *)
    case navigationGenericManeuver = 11
}

感想

びっくりするくらい簡単でした。

4
2
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
4
2