まゆたまガジェット開発逆引き辞典

電子工作やプログラミングのHowtoを逆引き形式で掲載しています。作りたいモノを決めて学んでいくスタイル。プログラマではないので、コードの汚さはお許しを。参照していないものに関しては、コピペ改変まったく問いません

近接センサを使う

iPhoneの前カメラ付近にある近接センサに手や顔などを近づけるとアクションが起こるものです。
どうやら近接センサが物体を検知しているときは、デフォルトで画面が真っ暗になるようです。
しかも相当手を近づけないと反応しないので、距離を測ることができず使いどころが難しいかもしれません。

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var sencerLabel: UILabel!
    @IBAction func sencerStop(sender: AnyObject) {
        
        //近接センサーのOFF
        myDevice.proximityMonitoringEnabled = false
        //近接センサーの監視を解除
        NSNotificationCenter.defaultCenter().removeObserver(self, name:UIDeviceProximityStateDidChangeNotification,
                object: nil)
    }
    
    
    //UIDeviceクラスを呼ぶ
    let myDevice: UIDevice = UIDevice.currentDevice()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //近接センサーのON
        myDevice.proximityMonitoringEnabled = true
        
        //近接センサーの通知設定
        NSNotificationCenter.defaultCenter()
            .addObserver(
                self,
                selector: "sencerAction:",
                name: "UIDeviceProximityStateDidChangeNotification",
                object: nil
        )
        //近接センサーを通知する
        NSNotificationCenter.defaultCenter()
            .postNotificationName(
                "UIDeviceProximityStateDidChangeNotification",
                object: nil
        )
        
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //近接センサの処理
    func sencerAction(notification: NSNotification){
        if myDevice.proximityState == true {
            //近づいた時
            print("近づいた");
            sencerLabel.text = "近づいた"
            
        }else{
            //離れた時
            print("離れた");
            sencerLabel.text = "離れた"
        }
    }

    

}