[ios] 아이폰 진동 만들기

iPhone을 한 번 진동하도록 설정하려면 어떻게해야합니까?

예를 들어, 플레이어가 생명을 잃거나 게임이 끝나면 iPhone이 진동합니다.



답변

iPhone Tutorial : iOS 장비의 기능을 확인하는 더 좋은 방법 “에서 :

매개 변수를 취하는 두 개의 유사한 기능이 있습니다 kSystemSoundID_Vibrate.

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

두 기능 모두 iPhone을 진동시킵니다. 그러나 진동을 지원하지 않는 장치에서 첫 번째 기능을 사용하면 경고음이 울립니다. 반면에 두 번째 기능은 지원되지 않는 장치에서는 아무 것도 수행하지 않습니다. 따라서 장치를 지속적으로 진동하려는 경우 기능 2를 사용하십시오.

먼저, AudioToolbox.framework빌드 단계에서 대상에 AudioToolbox 프레임 워크 를 추가하십시오 .

그런 다음이 헤더 파일을 가져 오십시오.

#import <AudioToolbox/AudioServices.h>


답변

스위프트 2.0 이상

AudioToolbox 지금을 제시 kSystemSoundID_VibrateA와 SystemSoundID코드가 그래서, 유형 :

import AudioToolbox.AudioServices

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)

여분의 캐스트 단계를 거치지 않고

(@Dov에 지원)

원래 답변 (Swift 1.x)

그리고 여기 Swift 에서 수행하는 방법이 있습니다 (나와 같은 문제가 발생한 경우)

Link AudioToolbox.frameworkto (프로젝트로 이동하여 대상 선택, 단계 빌드, 라이브러리와 바이너리 연결, 거기에 라이브러리 추가)

완료되면 :

import AudioToolbox.AudioServices

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

치즈 맛 SystemSoundID은 기본적으로 typealias(멋진 스위프트 typedef)입니다 UInt32.kSystemSoundID_Vibrate 정기적입니다 Int. 컴파일러에서 캐스트하려고 당신에게 오류를 제공 Int하는 UInt32,하지만 혼란 “SystemSoundID로 변환 할 수 없습니다”라고 오류가 읽습니다. 애플이 왜 그것을 스위프트 열거 형으로 만들지 않았습니까?

@ aponomarenko의 세부 사항에 들어가면 내 대답은 Swifters를위한 것입니다.


답변

오디오 서비스를 사용하는 간단한 방법은 다음과 같습니다.

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


답변

나는 어떤 방식으로 진동을 끈 장치에 대해 큰 문제가 있었지만 응용 프로그램 기능에 중요하기 때문에 관계없이 작동해야했습니다. 문서화 된 메소드 호출에 대한 정수이기 때문에 전달됩니다. 확인. 그래서 나는 잘 문서화 된 것 이외의 소리를 시도했습니다 : TUNER88 / iOSSystemSoundsLibrary

그런 다음 자동 스위치 나 장치의 설정에 관계없이 작동하는 1352를 우연히 발견했습니다 (Settings->vibrate on ring, vibrate on silent).

- (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);
     }
}


답변

중요 사항 : 향후 지원 중단 경고.

현재로 아이폰 OS 9.0API의 기능 설명 :

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

다음 내용을 포함합니다 :

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

올바른 방법은 다음 두 가지 중 하나를 사용하는 것입니다.

AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, nil)

또는

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

기억해 import AVFoundation


답변

iPhone 7/7 Plus 이상에서는 이러한 3 가지 햅틱 피드백 API를 사용하십시오.

사용 가능한 API

알림 :

let generator = UINotificationFeedbackGenerator()
generator.notificationOccured(style: .error)

사용 가능한 스타일은 .error, .success.warning입니다. 각각 고유 한 느낌이 있습니다.

로부터 문서 :

UIFeedbackGenerator성공, 실패 및 경고를 전달하기 위해 햅틱을 생성 하는 구체적인 하위 클래스입니다.

간단한 진동의 경우 :

let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccured()

사용 가능한 스타일은 .heavy, .medium.light입니다. 이것은 다양한 정도의 “경도”를 가진 단순한 진동입니다.

로부터 문서 :

UIFeedbackGenerator물리적 영향을 시뮬레이션하기 위해 햅틱을 생성 하는 구체적인 하위 클래스

사용자가 항목을 선택한 경우

let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()

이것은 모든 햅틱 중에서 가장 눈에 띄지 않으며 햅틱이 앱 경험을 인수하지 않아야 할 때 가장 적합합니다.

로부터 문서 :

UIFeedbackGenerator선택의 변화를 나타내는 햅틱을 생성 하는 구체적인 서브 클래스.

노트

이 API를 사용할 때 기억해야 할 것이 몇 가지 있습니다.

참고 A

실제로 햅틱을 만들지는 않습니다. 당신은 시스템이 요청 햅틱를 생성합니다. 시스템은 다음을 기반으로 결정합니다.

  • 장치에서 햅틱이 가능한 경우 (이 경우 Taptic Engine이 있는지 여부)
  • 앱이 오디오를 녹음 할 수 있는지 여부 (녹음 중에 원하지 않는 간섭을 방지하기 위해 햅틱이 생성되지 않음)
  • 시스템 설정에서 햅틱이 활성화되어 있는지 여부

따라서 시스템은 햅틱 요청이 가능하지 않으면 자동으로 무시합니다. 지원되지 않는 장치 때문인 경우 다음을 시도해보십시오.

func haptic() {
    // Get whether the device can generate haptics or not
    // If feedbackSupportLevel is nil, will assign 0
    let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int ?? 0

    switch feedbackSupportLevel {
    case 2:
        // 2 means the device has a Taptic Engine
        // Put Taptic Engine code here, using the APIs explained above

    case 1:
    // 1 means no Taptic Engine, but will support AudioToolbox
    // AudioToolbox code from the myriad of other answers!

    default: // 0
        // No haptic support
        // Do something else, like a beeping noise or LED flash instead of haptics
    }

switch– 의 주석을 대체하십시오.case 문 이 햅틱 생성 코드는 다른 iOS 장치로 이식 가능합니다. 가능한 최고 수준의 햅틱을 생성합니다.

비고 B

  • 햅틱 생성은 하드웨어 수준의 작업이므로 햅틱 생성 코드 를 호출 할 때와 실제로 발생하는 시점 사이에 지연 시간이있을 수 있습니다 . 이러한 이유로 Taptic Engine API에는 모두 prepare()준비 상태 가되는 방법이 있습니다. 게임 오버 사용 예 : 사용자의 체력이 매우 낮거나 근처에 위험한 몬스터가 있으면 게임이 종료 될 수 있습니다.
  • 몇 초 내에 햅틱을 생성하지 않으면 Taptic Engine은 배터리 수명을 절약하기 위해 유휴 상태로 돌아갑니다.

이 경우, Taptic Engine을 준비하면보다 품질이 좋고 반응이 빠른 환경을 만들 수 있습니다.

예를 들어 앱에서 팬 제스처 인식기를 사용하여 보이는 세계의 일부를 변경한다고 가정 해 보겠습니다. 사용자가 360도 회전 할 때 햅틱이 생성되기를 원합니다. 사용 방법은 다음과 같습니다 prepare().

@IBAction func userChangedViewablePortionOfWorld(_ gesture: UIPanGestureRecogniser!) {

    haptic = UIImpactFeedbackGenerator(style: .heavy)

    switch gesture.state {
        case .began:
            // The user started dragging the screen.
            haptic.prepare()

        case .changed:
            // The user trying to 'look' in another direction
            // Code to change viewable portion of the virtual world

            if virtualWorldViewpointDegreeMiddle = 360.0 {
                haptic.impactOccured()
            }

        default:
            break

} 


답변

Xamarin (monotouch) 프레임 워크를 사용하는 경우 전화

SystemSound.Vibrate.PlayAlertSound()