1

So I understand how to make the phone give haptic feedback through this tutorial. https://swifttom.com/2020/03/11/haptic-feedback-in-a-swiftui-button/

However, what I'm trying to figure out is how to make the iPhone actually vibrate, as in the vibration that occurs when receiving a phone call or a timer (from the default Clock app) going off while the phone is muted. I know this seems like I can find the answer easily on Google, but I honestly can't find a solution. Would be much appreciate if anyone can help.

import SwiftUI

struct ContentView: View {
    let generator = UINotificationFeedbackGenerator()
    var body: some View {
        VStack{
            Button("Press") {
                generator.notificationOccurred(.error) //I want vibration, not haptic feedback
            }
        }
    }
}
swiftNewb
  • 27
  • 5
  • Does this help? [how to run vibrate continuously in iphone?](https://stackoverflow.com/a/66040992/7129318) – Yrb Sep 08 '21 at 00:48
  • I just now looked over the link you provided. I haven't actually tried it out, but it looks like a valid solution. However, the solution I accepted here seems to be a more simple solution that uses less code. – swiftNewb Sep 08 '21 at 21:07
  • It is the answer from the link that I provided. Everyone simply googled it. – Yrb Sep 08 '21 at 22:14

3 Answers3

5

This should help a little I think. Try it out! Lmk if it works!

Source Code

import SwiftUI
import AudioToolbox


struct ContentView: View {
    var body: some View {
        VStack{
            
            Button("Press"){
                AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) {   }
               
            }
            
        }
        
    }
}
geethsg7
  • 205
  • 2
  • 11
2

Just call AudioServicesPlaySystemSound(kSystemSoundID_Vibrate). You may need to import the AudioToolbox framework.

Adam
  • 4,405
  • 16
  • 23
  • Hey, this is the solution I ended up going with. Thanks for the reply. I ended up choosing thetechie's similar answer, however, as it seemed more complete and therefore has more potential to help out future users. I still upvoted your post, though. – swiftNewb Sep 08 '21 at 17:17
-1

1. first you need to import AudioToolbox

i'm using vibration functionality when i tap button.

@IBAction func startVibration(_ sender: Any) { for _ in 1...5 { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) sleep(1) } }

its work fine.

2. make it an extension on UIDevice?

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

Now you can just call UIDevice.vibrate() as needed.

Karan Mehra
  • 339
  • 3
  • 12