programing

Swift를 사용하여 아이폰을 진동시키는 방법

stoneblock 2023. 4. 19. 21:52

Swift를 사용하여 아이폰을 진동시키는 방법

아이폰을 진동시켜야 하는데 스위프트에서 어떻게 진동시키는지 모르겠어요.Objective-C에는 다음과 같이 적습니다.

import AudioToolbox
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);

하지만 그것은 나에게 효과가 없다.

간단한 예:

import UIKit
import AudioToolbox

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))            
    }
}

휴대폰에 로드하면 진동합니다.원하는 기능이나 IBAtion에 넣을 수 있습니다.

코드 업데이트:

 AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { }

Apple 코드 문서 작성 시:

이 기능은 향후 릴리즈에서 폐지될 예정입니다.대신 Audio Services Play System Sound With Completion을 사용합니다.

메모: 진동으로 동작하지 않는 경우.사운드 및 합틱 설정에서 진동 활성화 여부 확인

Swift 4.2 갱신

아래 코드를 프로젝트에 삽입하기만 하면 됩니다.

사용.

Vibration.success.vibrate()

소스 코드

  enum Vibration {
        case error
        case success
        case warning
        case light
        case medium
        case heavy
        @available(iOS 13.0, *)
        case soft
        @available(iOS 13.0, *)
        case rigid
        case selection
        case oldSchool

        public func vibrate() {
            switch self {
            case .error:
                UINotificationFeedbackGenerator().notificationOccurred(.error)
            case .success:
                UINotificationFeedbackGenerator().notificationOccurred(.success)
            case .warning:
                UINotificationFeedbackGenerator().notificationOccurred(.warning)
            case .light:
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
            case .medium:
                UIImpactFeedbackGenerator(style: .medium).impactOccurred()
            case .heavy:
                UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
            case .soft:
                if #available(iOS 13.0, *) {
                    UIImpactFeedbackGenerator(style: .soft).impactOccurred()
                }
            case .rigid:
                if #available(iOS 13.0, *) {
                    UIImpactFeedbackGenerator(style: .rigid).impactOccurred()
                }
            case .selection:
                UISelectionFeedbackGenerator().selectionChanged()
            case .oldSchool:
                AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
            }
        }
    }

iPhone 7 또는 7 Plus의 iOS 10에서 다음을 시도해 보십시오.

let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()

기타 진동 유형:

import AudioToolbox

AudioServicesPlaySystemSound(1519) // Actuate "Peek" feedback (weak boom)
AudioServicesPlaySystemSound(1520) // Actuate "Pop" feedback (strong boom)
AudioServicesPlaySystemSound(1521) // Actuate "Nope" feedback (series of three weak booms)

Swift 4.2, 5.0

 if #available(iOS 10.0, *) {
      UIImpactFeedbackGenerator(style: .light).impactOccurred()
   } 

다른 스타일도 선택할 수 있습니다.

    style: .heavy
    style: .medium

    //Note: soft and rigid available in only iOS 13.0
    style: .soft
    style: .rigid

iOS 10.0+의 경우 UIFeedback Generator를 사용해 보십시오.

심플한 뷰 위의 컨트롤러는 테스트의 "싱글 뷰 앱"에서 뷰 컨트롤러를 교체하기만 하면 됩니다.

import UIKit

class ViewController: UIViewController {

    var i = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let btn = UIButton()
        self.view.addSubview(btn)
        btn.translatesAutoresizingMaskIntoConstraints = false

        btn.widthAnchor.constraint(equalToConstant: 160).isActive = true
        btn.heightAnchor.constraint(equalToConstant: 160).isActive = true
        btn.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        btn.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        btn.setTitle("Tap me!", for: .normal)
        btn.setTitleColor(UIColor.red, for: .normal)
        btn.addTarget(self, action: #selector(tapped), for: .touchUpInside)
    }

    @objc func tapped() {
        i += 1
        print("Running \(i)")

        switch i {
        case 1:
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.error)

        case 2:
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.success)

        case 3:
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.warning)

        case 4:
            let generator = UIImpactFeedbackGenerator(style: .light)
            generator.impactOccurred()
        case 5:
            let generator = UIImpactFeedbackGenerator(style: .medium)
            generator.impactOccurred()

        case 6:
            let generator = UIImpactFeedbackGenerator(style: .heavy)
            generator.impactOccurred()

        default:
            let generator = UISelectionFeedbackGenerator()
            generator.selectionChanged()
            i = 0
        }
    }
}

이것은 Xcode 7.1로 실행할 수 있습니다.

import UIKit
import AudioToolbox


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
    }
}

다음 중 하나를 사용하여 전화기를 진동시킬 수 있습니다.AudioServices또는Haptic Feedback.

// AudioServices
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))

// Haptic Feedback
UIImpactFeedbackGenerator(style: .medium).impactOccurred()

오픈 소스 프레임워크 Haptica를 체크해 주세요.둘 다 지원됩니다.Haptic Feedback,AudioServices독특한 진동 패턴을 가지고 있습니다.Swift 4.2, Xcode 10에서 동작

import AudioToolbox

extension UIDevice {
    static func vibrate() {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
    }
}

이제 그냥 전화하면 돼UIDevice.vibrate()필요에 따라서,

UINotification(유니메이션)Feedback Generator는 iOS 10부터 제공되며, Haptic v2와 연계하여 사용할 수 있습니다.다음 사항을 확인해 주십시오.

  let feedbackSupportLevel = UIDevice.current.value(forKey: "_feedbackSupportLevel") as? Int
        if #available(iOS 10.0, *), let feedbackSupportLevel = feedbackSupportLevel, feedbackSupportLevel > 1 {
            do { // 1
                let generator = UIImpactFeedbackGenerator(style: .medium)
                generator.impactOccurred()
            }

            do { // or 2
                let generator = UINotificationFeedbackGenerator()
                generator.notificationOccurred(.success)
            }
        } else {
            AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
        }
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))

언급URL : https://stackoverflow.com/questions/26455880/how-to-make-iphone-vibrate-using-swift