Created
September 3, 2019 07:09
-
-
Save Denismih/76e58caaa1bd1c49cc91ee91cdeb4e51 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func activateProximitySensor(isOn: Bool) { | |
let device = UIDevice.current | |
device.isProximityMonitoringEnabled = isOn | |
if isOn { | |
NotificationCenter.default.addObserver(self, selector: #selector(proximityStateDidChange), name: UIDevice.proximityStateDidChangeNotification, object: device) | |
let session = AVAudioSession.sharedInstance() | |
do{ | |
try session.setCategory(.playAndRecord) | |
try session.setActive(true) | |
try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) | |
} catch { | |
print ("\(#file) - \(#function) error: \(error.localizedDescription)") | |
} | |
} else { | |
NotificationCenter.default.removeObserver(self, name: UIDevice.proximityStateDidChangeNotification, object: device) | |
} | |
} | |
@objc func proximityStateDidChange(notification: NSNotification) { | |
if let device = notification.object as? UIDevice { | |
print(device) | |
let session = AVAudioSession.sharedInstance() | |
do{ | |
let routePort: AVAudioSessionPortDescription? = session.currentRoute.outputs.first | |
let portType = routePort?.portType | |
if let type = portType, type.rawValue == "Receiver" { | |
try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) | |
} else { | |
try session.overrideOutputAudioPort(AVAudioSession.PortOverride.none) | |
} | |
} catch { | |
print ("\(#file) - \(#function) error: \(error.localizedDescription)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment