首先,我是iOS开发的新手,所以请不要用客观的例子向我解释。
我的问题是:
我已经上过这堂课:
import UIKit
import CoreLocation
class BeaconRadar: NSObject, CLLocationManagerDelegate {
var manager : CLLocationManager!
var region : CLBeaconRegion!
var seenError = false
var locationFixAchieved = false
var locationStatus = "Not Started"
init() {
super.init()
var major = CLBeaconMajorValue( 10 )
var uuid = NSUUID( UUIDString: "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0" )
var id = "test"
manager = CLLocationManager()
region = CLBeaconRegion( proximityUUID: uuid, major: major, identifier: id )
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startRangingBeaconsInRegion(region)
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: AnyObject[], inRegion region: CLBeaconRegion! ){
if (locationFixAchieved == false) {
locationFixAchieved = true
println(beacons)
}
}
// If failed
func locationManager(_manager: CLLocationManager!, rangingBeaconsDidFailForRegion region: CLBeaconRegion!, withError error: NSError!){
manager.stopUpdatingLocation()
if (error) {
if (seenError == false) {
seenError = true
println("Error getting location")
}
}
}
// // authorization status
func locationManager(_manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus){
println("2")
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
println("Location Allowed")
// Start location services
manager.startUpdatingLocation()
} else {
println("Denied access: \(locationStatus)")
}
}
}
我的viewController是:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var location = BeaconRadar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我希望获得授权状态的实现功能中的一条消息。 (BeaconRadar中的最后一个)。但我一无所获。
如果我在viewController中而不是在新类中实现所有这些方法 (即:
class ViewController: UIViewController, CLLocationManagerDelegate {
.....
}
然后它会正常工作...... 我错过了什么吗?
答案 0 :(得分:2)
您已将BeaconRadar
实例声明为viewDidLoad
内的局部变量,因此只要此函数退出,BeaconRadar实例就会被释放。
您应该将BeaconRegion变量移出函数 -
class ViewController: UIViewController {
let location = BeaconRadar()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}