swift 3.0 代码实现摇一摇(防微信)
iOS 系统中自带了摇一摇监测功能,这里我们只需要使用即可,当让业界也有其他方式来实现摇一摇的方法,比如监听手机晃动幅度来完成。
var player: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
self.setUI()
/**
开启摇动感应
*/
UIApplication.shared.applicationSupportsShakeToEdit = true
becomeFirstResponder()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
开始摇动
*/
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
print("开始摇动")
//开始动画
UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: UIViewKeyframeAnimationOptions.beginFromCurrentState, animations: { () -> Void in
self.rockupImage.frame.origin.y -= 80
self.rockdownImage.frame.origin.y += 80
}, completion: nil)
/// 设置音效
let path1 = Bundle.main.path(forResource: "rock", ofType:"mp3")
let data1 = try? Data(contentsOf: URL(fileURLWithPath: path1!))
self.player = try? AVAudioPlayer(data: data1!)
self.player?.delegate = self
self.player?.updateMeters()//更新数据
self.player?.prepareToPlay()//准备数据
self.player?.play()
//结束动画
UIView.animateKeyframes(withDuration: 0.5, delay: 1.0, options: UIViewKeyframeAnimationOptions.beginFromCurrentState, animations: { () -> Void in
self.rockupImage.frame.origin.y += 80
self.rockdownImage.frame.origin.y -= 80
}, completion: nil)
}
/**
取消摇动
*/
override func motionCancelled(_ motion: UIEventSubtype, with event: UIEvent?) {
print("取消摇动")
}
/**
摇动结束
*/
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
print("摇动结束")
///此处设置摇一摇需要实现的功能
/// 设置音效
let path = Bundle.main.path(forResource: "rock_end", ofType:"mp3")
let data = try? Data(contentsOf: URL(fileURLWithPath: path!))
self.player = try? AVAudioPlayer(data: data!)
self.player?.delegate = self
self.player?.updateMeters()//更新数据
self.player?.prepareToPlay()//准备数据
self.player?.play()
}
func setUI(){
self.view.backgroundColor = UIColor.colorWithHex(hexColor: 0xf2f2f2)
self.view.addSubview(self.rockupImage)
self.view.addSubview(self.rockdownImage)
self.rockupImage.snp.makeConstraints { (make) in
make.width.equalTo(100)
make.height.equalTo(50)
make.centerX.equalTo(self.view.snp.centerX)
make.bottom.equalTo(self.view.snp.centerY)
}
self.rockupImage.contentMode = .scaleAspectFit
self.rockupImage.image = UIImage.init(named: "rock_up-1.png")
self.rockdownImage.snp.makeConstraints { (make) in
make.width.equalTo(100)
make.height.equalTo(50)
make.centerX.equalTo(self.view.snp.centerX)
make.top.equalTo(self.view.snp.centerY)
}
self.rockdownImage.contentMode = .scaleAspectFit
self.rockdownImage.image = UIImage.init(named: "rock_down-1.png")
}
fileprivate var rockupImage: UIImageView = {
let view = UIImageView()
return view
}()
fileprivate var rockdownImage: UIImageView = {
let view = UIImageView()
return view
}()
fileprivate lazy var width = UIScreen.main.bounds.width