お断り
この記事は自分専用メモなのですごい初歩的な事しか書いていませんがご了承下さい。
確認環境
Interface:Storyboard
Life Cycle:UIKit App Delegate
Language:Swift
◉Use Core Data
__○Host in CloudKit
◉Include Tests
この記事で出来る様になる事
振られた時の処理が書けるよういになる
実装
UIの実装
無し!!
コードの実装
import UIKit
import CoreMotion
import AVFoundation
class ViewController: UIViewController {
let MotionSensor = CMMotionManager()
var sound:AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
getAccelerometer()
sound = try? AVAudioPlayer(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "test", ofType: "wav")!))
// Do any additional setup after loading the view.
}
func get() {
sound.stop()
sound.currentTime = 0
sound.play()
}
func getAccelerometer() {
MotionSensor.accelerometerUpdateInterval = 0.2
MotionSensor.startAccelerometerUpdates(to: OperationQueue.current!, withHandler: {
accelerometerData,error in
let x = accelerometerData!.acceleration.x
let y = accelerometerData!.acceleration.y
let z = accelerometerData!.acceleration.z
let synthetic = (x * x) + (y * y) + (z * z)
if synthetic >= 6 {
self.get()
}
})
}
}
**let MotionSensor = CMMotionManager()**ではCMMotionManagerのインスタンスMotionSensorを作る
**func getAccelerometer()**この関数内に振られたか調べるプログラムを書いて行く
MotionSensor.accelerometerUpdateInterval = 0.2加速度を確認する間隔を0.2秒ごとに確認する
let x = accelerometerData!.acceleration.xではxの加速度を取得する
**let synthetic = (x * x) + (y * y) + (z * z)**ではx、y、zの加速度を掛け合わせて変数syntheticに代入する
後はif文で一定値を越えたら音を鳴らす関数を呼び出す
細かいところ
めんどくさいので細かい所はappleのリファレンスを見て
https://developer.apple.com/documentation/coremotion