今天给大家分享下微信摇一摇的实现,附带震动效果以及添加摇一摇时的指定音乐
//
// ViewController.m
// 摇一摇
//
// Created by Amydom on 16/9/4.
// Copyright © 2016年 Amydom. All rights reserved.
//
#import "ViewController.h"
#import "ShakeController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController (){
AVAudioPlayer *player;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self setUpShake];
}
//创建摇一摇
- (void)setUpShake{
//设置允许摇一摇
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;
//并让自己成为第一响应者
[self becomeFirstResponder];
UIButton * shakeBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[shakeBtn setTitle:@"摇一摇" forState:UIControlStateNormal];
[shakeBtn setBackgroundColor:[UIColor lightGrayColor]];
[self.view addSubview:shakeBtn];
[shakeBtn addTarget:self action:@selector(shakeAction) forControlEvents:UIControlEventTouchUpInside];
}
- (void)shakeAction{
ShakeController *shakeVC = [[ShakeController alloc]init];
[self.navigationController pushViewController:shakeVC animated:NO];
}
#pragma make - 摇一摇相关方法
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"开始摇动");
//振动效果
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
if (event.subtype == UIEventSubtypeMotionShake) {
//选取音乐
NSString *soundFielPath = [[NSBundle mainBundle] pathForResource:@"buyao" ofType:@"wav"];
NSURL * fileUrl = [[NSURL alloc]initFileURLWithPath:soundFielPath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
player = newPlayer;
[player prepareToPlay];
//开始播放
[player play];
}
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"取消摇动");
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
//判断是否摇动结束
if (event.subtype == UIEventSubtypeMotionShake) {
NSLog(@"摇动结束");
NSString *soundFielPath = [[NSBundle mainBundle] pathForResource:@"buyao" ofType:@"wav"];
NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:soundFielPath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
player = newPlayer;
[player prepareToPlay];
[player play];
NSLog(@"摇到 xx");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
有些逻辑需要在摇晃结束或者开始时自行添加,这里就不多写了