(初心者向け)Swift3.0で初アプリ - ビーコンを検出してみる

Swift3.0を使って簡単なiPhoneアプリを作ってみます
[初心者向け）Swift3.0で簡単なiPhoneアプリを作ってみる](http://qiita.com/egplnt/items/e8da2b9af1037e179a57)で作ったシンプルなSwift3.0アプリでビーコンを検出してみます

#1. ビーコンを用意します
- ビーコンを用意し、UUID、major、minor値を確認します
- 手近にビーコンがない場合、iPhoneやMacbookをビーコンにすることができます
- Macbookからビーコンを発信する方法→[SwiftとiBeaconを使ってお母さんが自分の部屋に近づいて来た事を警告するアプリをつくる](http://qiita.com/oggata/items/5de43d71692d1abcff7c)
- iPhoneからビーコンを発信する方法→[手軽にビーコンの動作を体験できる「Beacon入門」アプリが登場！](http://beaconlabo.com/2016/03/2312/)

#2. アプリを用意します
- ビーコンを受信するアプリを作成します
- XcodeでSwiftアプリを用意します
- ラベルを２つ、ボタンを２つ用意します
- ViewController.swiftに下記のコードをコピペします

```swift:ビーコン検出サンプルアプリ
import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    
    var myLocationManager:CLLocationManager!
    var myBeaconRegion:CLBeaconRegion!
    var beaconUuids: NSMutableArray!
    var beaconDetails: NSMutableArray!
    
    let UUIDList = [
        "AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA",
        "12345678-1234-1234-1234-123456789012"
    ]
    @IBOutlet weak var label1: UILabel!
    @IBAction func button1(_ sender: UIButton) {
        if (label1.text == "Immediate") {
            label2.text = "ポイントげっとしましたー！"
        }
    }
    @IBOutlet weak var label2: UILabel!
    @IBAction func button2(_ sender: UIButton) {
        label2.text = ""
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        myLocationManager = CLLocationManager()
        myLocationManager.delegate = self
        myLocationManager.desiredAccuracy = kCLLocationAccuracyBest
        myLocationManager.distanceFilter = 1
        let status = CLLocationManager.authorizationStatus()
        print("CLAuthorizedStatus: \(status.rawValue)");
        if(status == .notDetermined) {
            myLocationManager.requestAlwaysAuthorization()
        }
        beaconUuids = NSMutableArray()
        beaconDetails = NSMutableArray()
    }
    
    private func startMyMonitoring() {
        for i in 0 ..< UUIDList.count {
            let uuid: NSUUID! = NSUUID(uuidString: "\(UUIDList[i].lowercased())")
            let identifierStr: String = "abcde\(i)"
            myBeaconRegion = CLBeaconRegion(proximityUUID: uuid as UUID, identifier: identifierStr)
            myBeaconRegion.notifyEntryStateOnDisplay = false
            myBeaconRegion.notifyOnEntry = true
            myBeaconRegion.notifyOnExit = true
            myLocationManager.startMonitoring(for: myBeaconRegion)
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("didChangeAuthorizationStatus");
        switch (status) {
        case .notDetermined:
            print("not determined")
            break
        case .restricted:
            print("restricted")
            break
        case .denied:
            print("denied")
            break
        case .authorizedAlways:
            print("authorizedAlways")
            startMyMonitoring()
            break
        case .authorizedWhenInUse:
            print("authorizedWhenInUse")
            startMyMonitoring()
            break
        }
    }
 
    func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
        manager.requestState(for: region);
    }
    
    func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
        switch (state) {
        case .inside:
            print("iBeacon inside");
            manager.startRangingBeacons(in: region as! CLBeaconRegion)
            break;
        case .outside:
            print("iBeacon outside")
            break;
        case .unknown:
            print("iBeacon unknown")
            break;
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
        beaconUuids = NSMutableArray()
        beaconDetails = NSMutableArray()
        if(beacons.count > 0){
            for i in 0 ..< beacons.count {
                let beacon = beacons[i]
                let beaconUUID = beacon.proximityUUID;
                let minorID = beacon.minor;
                let majorID = beacon.major;
                let rssi = beacon.rssi;
                var proximity = ""
                switch (beacon.proximity) {
                case CLProximity.unknown :
                    print("Proximity: Unknown");
                    proximity = "Unknown"
                    break
                case CLProximity.far:
                    print("Proximity: Far");
                    proximity = "Far"
                    break
                case CLProximity.near:
                    print("Proximity: Near");
                    proximity = "Near"
                    break
                case CLProximity.immediate:
                    print("Proximity: Immediate");
                    proximity = "Immediate"
                    break
                }
                beaconUuids.add(beaconUUID.uuidString)
                var myBeaconDetails = "Major: \(majorID) "
                myBeaconDetails += "Minor: \(minorID) "
                myBeaconDetails += "Proximity:\(proximity) "
                myBeaconDetails += "RSSI:\(rssi)"
                print(myBeaconDetails)
                beaconDetails.add(myBeaconDetails)
                label1.text = proximity
            }
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        print("didEnterRegion: iBeacon found");
        manager.startRangingBeacons(in: region as! CLBeaconRegion)
    }
    
    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        print("didExitRegion: iBeacon lost");
        manager.stopRangingBeacons(in: region as! CLBeaconRegion)
    }
}

```
- 使用するビーコンのUUID/Major/Minorを上記のViewController.swiftのUUIDリストと置き換えます
- 上記のViewController.swiftのlabel1、label2、button1、button2を、用意したラベル（ｘ２）、ボタン（ｘ２）と置き換えて接続し直します
- 位置情報を使用可能にするため、ナビゲーターで「info.plist」を選択し、
    - Swift3であれば：　「Privacy - Location Always Usage Description」を追加します
    - Swift4であれば：　「Privacy - Location Always and When In Use Usage Description」と[Privacy - Location When In Use Usage Description」を追加します

![スクリーンショット 2017-06-21 20.26.02.png](https://qiita-image-store.s3.amazonaws.com/0/125842/228eabb6-1e05-7027-5c7e-c34ee0085f4d.png)




#4. iPhoneで確認します
- iPhoneにデプロイし、稼働を確認します

<img width="375" alt="IMG_3592.PNG" src="https://qiita-image-store.s3.amazonaws.com/0/125842/bc13de59-d913-0868-3ba3-38b551ad70d6.png">

#次のステップ

#関連ページ