Created
          May 29, 2020 11:49 
        
      - 
      
- 
        Save skl/a093291abc0a90a640e50f78888456e7 to your computer and use it in GitHub Desktop. 
    iOS SwiftUI proximity observer example
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | import SwiftUI | |
| import UIKit | |
| class ProximityObserver { | |
| @objc func didChange(notification: NSNotification) { | |
| print("MyView::ProximityObserver.didChange") | |
| if let device = notification.object as? UIDevice { | |
| print(device.proximityState) | |
| } | |
| } | |
| } | |
| struct MyView: View { | |
| var proximityObserver = ProximityObserver() | |
| func activateProximitySensor() { | |
| print("MyView::activateProximitySensor") | |
| UIDevice.current.isProximityMonitoringEnabled = true | |
| if UIDevice.current.isProximityMonitoringEnabled { | |
| NotificationCenter.default.addObserver(proximityObserver, selector: #selector(proximityObserver.didChange), name: UIDevice.proximityStateDidChangeNotification, object: UIDevice.current) | |
| } | |
| } | |
| func deactivateProximitySensor() { | |
| print("MyView::deactivateProximitySensor") | |
| UIDevice.current.isProximityMonitoringEnabled = false | |
| NotificationCenter.default.removeObserver(proximityObserver, name: UIDevice.proximityStateDidChangeNotification, object: UIDevice.current) | |
| } | |
| var body: some View { | |
| Text("Foo") | |
| .onAppear() { | |
| self.activateProximitySensor() | |
| }.onDisappear() { | |
| self.deactivateProximitySensor() | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment