您的位置:首页 > 移动开发 > IOS开发

iOS摇一摇

2015-11-29 00:00 281 查看
摘要: iOS摇一摇

一、直接用系统自带的motionBegan方法
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
假如程序不响应此方法,试着加入下面方法:
-(BOOL)canBecomeFirstResponder
{
return YES;
}
如果还不行,建议用第二种方法。
二、motionBegan+通知的方法
1.在Appdelegate里写motionBegan方法
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
[[NSNotificationCenter defaultCenter]postNotificationName:@"shake" object:self];
}
2.在需要接收通知的页面添加通知[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shakeAction) name:@"shake" object:nil];
写在viewDidLoad里即可。这里的shakeAction就是摇一摇需要调用的方法,自己修改,通知名字对应就好,可自由修改。

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "ShakeViewController.h"

@interface ShakeViewController ()
@property (nonatomic, strong)AVAudioPlayer *player;
@end

@implementation ShakeViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.titleLabel.text = @"摇一摇";
}
- (BOOL)becomeFirstResponder{
return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
[self shake];

[self sound];
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{

}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{

}
- (void)shake{
AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
}

- (void)sound{

/*
SystemSoundID systemID;

NSString *path = [[NSBundle mainBundle] pathForResource:@"shake_sound_male.wav" ofType:@""];

NSURL *url = [NSURL URLWithString:path];
//NSURL *url = [NSURL fileURLWithPath:path];

AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &systemID);

AudioServicesPlaySystemSound(systemID);
*/

NSString *path = [[NSBundle mainBundle] pathForResource:@"shake_sound_male.wav" ofType:@""];

NSURL *url = [NSURL fileURLWithPath:path];

_player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

[_player prepareToPlay];

[_player play];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: