2016-07-06 52 views
1

我試圖製作一個顯示信標鄰近度的應用程序。我做了一個label來接收這些數據,但是我不能,而且我想只顯示「接近」而不是顯示在控制檯中的所有這些數據。我嘗試使用beacons[3],但該程序給我一個錯誤。控制檯打印用Swift 2標記

import UIKit 
import CoreLocation 

class ViewController: UIViewController, CLLocationManagerDelegate { 

    @IBOutlet var metrosBeacon: UILabel! 
    let locationManager = CLLocationManager() 
    let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "FDA50693-A4E2-4FB1-AFCF-C6EB07647828")!, identifier: "MKT BEACONS") 
    // Note: make sure you replace the keys here with your own beacons' Minor Values 


    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     locationManager.delegate = self 
     if (CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse) { 
      locationManager.requestWhenInUseAuthorization() 
     } 
     locationManager.startRangingBeaconsInRegion(region) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion){ 
     print (beacons) 
     metrosBeacon.text = "/(beacons)" 

    }} 

控制檯數據:

[CLBeacon(UUID:< __NSConcreteUUID 0x12ee586c0> FDA50693-A4E2-4FB1-AFCF-C6EB07647828,主要:10004,次要:54480,接近:1 +/- 0.05m,rssi:-32)]

謝謝大家!

+0

你打電話得到的錯誤標[3]可能會發生,因爲比少四個信標是可見的。我會在他的答案中使用@ eric-d顯示的解決方案,您可以訪問beacons.first來獲取第一個,然後訪問其鄰近區域。 – davidgyoung

回答

2

我們locationManager的簽名看到beacons是CLBeacon對象的數組:

func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) 

而且我們看到,你得到的陣列中的一個對象:

[CLBeacon(UUID: < __NSConcreteUUID 0x12ee586c0> FDA50693-A4E2-4FB1-AFCF-C6EB07647828,主要:10004,次要:54480,接近:1個+/-0.05米,RSSI:-32)]

因此,得到數組這第一個對象,然後得到該屬性的值:

if let beacon = beacons.first { 
    print(beacon.proximity) 
} 

當然,如果你在陣列中有幾個信標,你可以使用一個循環:

for beacon in beacons { 
    print(beacon.proximity) 
} 
0

CLBeacon是​​的子類,因此有一個名爲description()的方法,該方法返回NSString,其中包含該對象的說明。

當你調用print(beacons),你在類型[CLBeacon]的參數調用print(又名Array<CLBeacon >,或CLBeacon對象的數組)。 print本身不知道如何打印CLBeacon對象,因此它會要求CLBeacondescription(),並打印該對象。

輸出:

[CLBeacon(UUID:< __NSConcreteUUID 0x12ee586c0> FDA50693-A4E2-4FB1-AFCF-C6EB07647828,主要:10004,次要:54480,接近:1個+/-0.05米,RSSI :-32)]

表示單個CLBeacon object, whose description`的陣列是:

CLBeacon(UUID:< __NSConcreteUUID 0x12ee586c0> FD A50693-A4E2-4FB1-AFCF-C6EB07647828,major:10004,minor:54480,接近度:1 +/- 0。05米,RSSI:-32)

得到公正的接近,我們可以看看到class documentation for CLBeacon,並看到它有一個proximity變量,我們可以得到的。

我們可以打印所有接近的東西,如:在標

信標{ 打印(beacon.proximity) }