iPhoneのバイブレーション機能を用いるには?
システムサウンドにバイブレーションさせるものがあるのでそれを用います。
System Sound Services Reference
• AudioToolboxをimportしたうえで、バイブレーション用サウンドを指定して鳴らすことで、振動させることができます。
import AudioToolbox
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
バイブレーションのサンプル
Startボタンを押すと3秒間隔で振動し続けるサンプルを作成しました。(Stopボタンを押すと止まります)
Single View Applicationで開発。
StartボタンとViewController.swift間をActionで結びつける
@IBAction func pushStartOrStopBtn(sender: AnyObject) {
}Startボタンが押されると、Timerが起動します。
Timerは3秒間隔で、システムサウンドによるバイブレーションを実行しています。
また、ボタンは押されるごとに、”Start”と”Stop”の表記を切り替えています。
Stopボタンが押されると、Timerを無効にします。
ViewController.swift
//
// ViewController.swift
// Vibration Demo
//
// Created by KUWAJIMA MITSURU on 2015/11/13.
// Copyright © 2015年 nackpan. All rights reserved.
//
import UIKit
import AudioToolbox
class ViewController: UIViewController {
var timer = NSTimer()
var nowPlaying = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pushStartOrStopBtn(sender: AnyObject) {
let btn = sender as! UIButton
if nowPlaying {
pushStopBtn(btn)
} else {
pushStartBtn(btn)
}
}
func pushStartBtn(btn: UIButton) {
timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "vibrate:", userInfo: nil, repeats: true)
timer.fire()
btn.setTitle("Stop", forState: UIControlState.Normal)
nowPlaying = true
}
func vibrate(timer: NSTimer) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
func pushStopBtn(btn: UIButton) {
timer.invalidate()
btn.setTitle("Start", forState: UIControlState.Normal)
nowPlaying = false
}
}
