2016-07-06 77 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) }