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

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


当前回答

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

SystemSound.Vibrate.PlayAlertSound()

其他回答

对于以某种方式关闭振动的设备,我遇到了很大的麻烦,但我们无论如何都需要它工作,因为它对我们的应用程序功能至关重要,而且由于它只是文档方法调用的整数,因此它将通过验证。所以我已经尝试了一些在TUNER88/ iossystemsoundlibrary之外的声音

然后我偶然发现了1352,不管静音开关或设备上的设置(设置->震动铃声,震动静音),它都在工作。

- (void)vibratePhone;
{
     if([[UIDevice currentDevice].model isEqualToString:@"iPhone"])
     {
         AudioServicesPlaySystemSound (1352); //works ALWAYS as of this post
     }
     else
     {
          // Not an iPhone, so doesn't have vibrate
          // play the less annoying tick noise or one of your own
          AudioServicesPlayAlertSound (1105);
     }
}

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

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

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

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

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

然后,导入这个头文件:

#import <AudioToolbox/AudioServices.h>

Swift 2。0 +

AudioToolbox现在将kSystemSoundID_Vibrate表示为SystemSoundID类型,因此代码如下:

import AudioToolbox.AudioServices

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)

而不必通过额外的强制转换步骤

(@Dov的道具)

原始答案(Swift 1.x)

下面是你如何在Swift上做这件事(以防你遇到和我一样的麻烦)

链接AudioToolbox.framework(转到你的项目,选择你的目标,构建阶段,链接二进制库,在那里添加库)

一旦完成:

import AudioToolbox.AudioServices

// Use either of these
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

SystemSoundID基本上是UInt32的类型别名(花哨的swift typedef),而kSystemSoundID_Vibrate是一个常规Int。编译器给你一个错误,试图从Int转换到UInt32,但错误读为“不能转换为SystemSoundID”,这是令人困惑的。苹果为什么不直接把它做成Swift enum,我真搞不懂。

@aponomarenko详细介绍了,我的答案只是给斯威夫特的。

一个简单的方法是使用音频服务:

#import <AudioToolbox/AudioToolbox.h> 
...    
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

你可以使用

1) AudioServicesPlayAlertSound (kSystemSoundID_Vibrate);

iPhone和一些新款ipod。

2) AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);

ipad。