0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-08-22

Swift3.0を使って簡単なiPhoneアプリを作ってみます
初心者向け)Swift3.0で簡単なiPhoneアプリを作ってみるで作ったシンプルなSwift3.0アプリでビーコンを検出してみます

#1. ビーコンを用意します

#2. アプリを用意します

  • ビーコンを受信するアプリを作成します
  • XcodeでSwiftアプリを用意します
  • ラベルを2つ、ボタンを2つ用意します
  • ViewController.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を、用意したラベル(x2)、ボタン(x2)と置き換えて接続し直します
  • 位置情報を使用可能にするため、ナビゲーターで「info.plist」を選択し、「Privacy - Location Always Usage Description」を追加します

スクリーンショット 2017-06-21 20.26.02.png

#4. iPhoneで確認します

  • iPhoneにデプロイし、稼働を確認します
IMG_3592.PNG

#次のステップ
スタンプラリーアプリを作ってみる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?