我一直在关注使用Swift创建Beacon感应应用程序的指南,但是自从更新Xcode并将代码更新到Swift 3.0后,我遇到了致命的错误。
通过函数我认为startScanning函数存在问题,当它触发时我会收到致命的错误消息。
任何有助于提供帮助的提示都将受到高度赞赏:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var distanceLabel: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
view.backgroundColor = UIColor.gray
print("did load")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.authorizedAlways{
print("status authorized")
if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self){
print("is monitoring")
if CLLocationManager.isRangingAvailable() {
print("scanning")
startScanning()
}
}
}
}
func startScanning() {
print("start Scanning")
let uuid = NSUUID(uuidString: "695e5f08824c785cadc72e1dde23be04")
let beaconRegion = CLBeaconRegion(proximityUUID: uuid as! UUID, identifier: "MyBeacon")
locationManager.startMonitoring(for: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
}
func updateDistance(distance: CLProximity){
UIView.animate(withDuration: 1) { [unowned self] in
switch distance {
case .unknown:
self.view.backgroundColor = UIColor.gray
self.distanceLabel.text = "UNKNOWN"
print("distance Unknown")
case .far:
self.view.backgroundColor = UIColor.blue
self.distanceLabel.text = "FAR"
print("distance Far")
case .near:
self.view.backgroundColor = UIColor.orange
self.distanceLabel.text = "NEAR"
print("distance Near")
case .immediate:
self.view.backgroundColor = UIColor.red
self.distanceLabel.text = "BOOM!"
print("distance Immediate")
}
}
}
func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) {
if beacons.count > 0 {
let beacon = beacons.first! as CLBeacon
updateDistance(distance: beacon.proximity)
print("found more than one beacon")
} else {
updateDistance(distance: .unknown)
print("found only one beacon")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:3)
问题是您的UUID格式错误,因此该行无法解析它,为变量uuid
分配nil:
let uuid = NSUUID(uuidString: "695e5f08824c785cadc72e1dde23be04")
程序将使用uuid as! UUID
操作崩溃,因为!如果有零值,将会崩溃。
要解决此问题,您需要在UUID字符串中的适当位置添加短划线。你也应该避免使用!运算符强制在Swift中解包可选变量,因为它可能导致这样的崩溃。试试这个:
if let uuid = NSUUID(uuidString: "695e5f08-824c-785c-adc7-2e1dde23be04") {
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, identifier: "MyBeacon")
locationManager.startMonitoring(for: beaconRegion)
locationManager.startRangingBeacons(in: beaconRegion)
}
else {
NSLog("Invalid UUID format")
}
运行时检查代码是否没有按“无效的UUID格式”路径。