如何将iPhone设置为震动一次?

例如,当玩家失去一条生命或游戏结束时,iPhone应该震动。


当前回答

在iOS 10和更新的iphone上,你也可以使用触觉API。这种触觉反馈比AudioToolbox API更柔和。

对于你的GAME OVER场景,一个重UI影响反馈应该是合适的。

UIImpactFeedbackGenerator(风格:.heavy) .impactOccurred ()

你可以使用其他的触觉反馈方式。

其他回答

如果您正在使用Xamarin (monotouch)框架,只需调用

SystemSound.Vibrate.PlayAlertSound()

摘自“iPhone教程:检查iOS设备功能的更好方法”:

这里有两个看似相似的函数,它们都带有参数kSystemSoundID_Vibrate:

1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

这两个功能都能使iPhone震动。但是,当你用第一个 功能在不支持振动的设备上,它会发出哔哔声 声音。另一方面,第二个函数不做任何操作 不受支持的设备。所以如果你要振动这个设备 连续地,作为一个警告,常识说,使用函数2。

首先,在构建阶段中将AudioToolbox框架AudioToolbox.framework添加到目标中。

然后,导入这个头文件:

#import <AudioToolbox/AudioServices.h>

重要提示:未来弃用警报。 从iOS 9.0开始,API函数描述如下:

AudioServicesPlaySystemSound(inSystemSoundID: SystemSoundID)
AudioServicesPlayAlertSound(inSystemSoundID: SystemSoundID)

包括以下说明:

This function will be deprecated in a future release.
Use AudioServicesPlayAlertSoundWithCompletion or  
AudioServicesPlaySystemSoundWithCompletion instead.

正确的方法是使用以下两种:

AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, nil)

or

AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate) {
 //your callback code when the vibration is done (it may not vibrate in iPod, but this callback will be always called)
}

记得导入AVFoundation

在我的例子中,我使用的是AVCaptureSession。 AudioToolbox是在项目的构建阶段,它被导入,但仍然不能工作。为了使它工作,我在振动之前停止会话,然后继续。

#import <AudioToolbox/AudioToolbox.h>
...
@property (nonatomic) AVCaptureSession *session;
...
- (void)vibratePhone;
{
  [self.session stopRunning];
     NSLog(@"vibratePhone %@",@"here");
    if([[UIDevice currentDevice].model isEqualToString:@"iPhone"])
    {
        AudioServicesPlaySystemSound (kSystemSoundID_Vibrate); 
    }
    else
    {
        AudioServicesPlayAlertSound (kSystemSoundID_Vibrate);
    }
  [self.session startRunning];
}

在iOS 10和更新的iphone上,你也可以使用触觉API。这种触觉反馈比AudioToolbox API更柔和。

对于你的GAME OVER场景,一个重UI影响反馈应该是合适的。

UIImpactFeedbackGenerator(风格:.heavy) .impactOccurred ()

你可以使用其他的触觉反馈方式。