AVAudioSession Swift

I am trying to write a fast iOS application that will record the voice of users. I wrote the following code in swift, however it does not ask for microphone permission from the user. It is imprinted, but it never records audio, and in the settings panel in privacy mode, it does not display the application. How to request write permissions in swift?

var session: AVAudioSession = AVAudioSession.sharedInstance() session.requestRecordPermission({(granted: Bool)-> Void in if granted { println(" granted") session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) session.setActive(true, error: nil) self.recorder.record() }else{ println("not granted") } }) 
+8
ios swift avaudioplayer avaudiorecorder avaudiosession
source share
3 answers

Starting with iOS 7, you need to check if it responds to the requestRecordPermission: selector requestRecordPermission:

I tested this code on iPhone 5S with iOS 8 Beta and it works great. Once you give permission, the system will no longer request it.

It is worth saying that he did not request permission when using the simulator .

This is the code I tried and works:

 if (session.respondsToSelector("requestRecordPermission:")) { AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in if granted { println("granted") session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) session.setActive(true, error: nil) self.recorder () } else{ println("not granted") } }) } 
+13
source share

For Swift 3 :

 let session = AVAudioSession.sharedInstance() if (session.responds(to: #selector(AVAudioSession.requestRecordPermission(_:)))) { AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in if granted { Linphone.manager.callUser(username: username) print("granted") do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord) try session.setActive(true) } catch { print("Couldn't set Audio session category") } } else{ print("not granted") } }) } 
+3
source share

Swift 5

 var session: AVAudioSession = AVAudioSession.sharedInstance() @IBAction func btnmike(_ sender: Any) { // let session = AVAudioSession.sharedInstance() if (session.responds(to: #selector(AVAudioSession.requestRecordPermission(_:)))) { AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in if granted { print("granted") do { try self.session.setCategory(AVAudioSessionCategoryPlayAndRecord) try self.session.setActive(true) } catch { print("Couldn't set Audio session category") } } else{ print("not granted") } }) } } 
+2
source share

All Articles