为什么locationManager didUpdateLocation不起作用?

时间:2015-08-18 12:35:26

标签: ios swift core-location cllocationmanager

将CoreLocation.Foundation添加到BuildPhase并导入到文件顶部,如果我将以下内容放入带有按钮的视图控制器中,我可以获取位置信息:

@IBAction func locationButton(sender: AnyObject) {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

它继承了带有CLGeocoder()的locationManager didUpdateLocations。reverseGeocodeLocation completionHandler在另一个函数中显示位置信息 - 这是有效的。

但是,当我尝试在我的数据模型中传输相同的代码时,它不起作用。我使用以下内容设置模型:

import CoreLocation

class Record: NSObject, CLLocationManagerDelegate
{
    let locationManager = CLLocationManager()

因为没有按钮,我将locationManager代码放入:

        override init()
{
    iD = NSUUID().UUIDString

    super.init()

    if (CLLocationManager.locationServicesEnabled())
    {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()

        switch CLLocationManager.authorizationStatus() {
        case .AuthorizedWhenInUse, .AuthorizedAlways:
            locationManager.startUpdatingLocation()
        case .NotDetermined:
            locationManager.requestWhenInUseAuthorization() // or request always if you need it
        case .Restricted, .Denied:
            print("tell users that they need to enable access in settings")
        default:
            break
        }
        print("Location services available")
        if CLLocationManager.authorizationStatus() == .NotDetermined
        {
            print("Still Not Determined")
        }
    } else { print("Location services not available") }

}

我获得'位置服务'。但是下面的代码从不向控制台打印任何内容,也没有调用函数toSetLocationStamped。

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
    print("started location man")
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler:        //pass the location co-ordinates
        {
            (placemarks, error) -> Void in

            if (error != nil)
            {
                println("Reverse geocoder failed with error" + error.localizedDescription)
                return
            }

            if placemarks.count > 0         //process the location array (placemarks)
            {
                let pm = placemarks[0] as! CLPlacemark
                self.toSetLocationStamped(pm)
                print("got here")
            } else
            {
                println("Problem receiving data from geocoder")
            }
    })
}

如果我使用简单的打印日志来放置类记录,则没有输出。

deinit
{
    print("deinit")
}

我正在初始化一个dummyRecord:来自MasterViewController类中所需的init的记录:

class MasterViewController: UITableViewController
{
var records = [Record]()
var subjectDescription: String?

// weak var delegate: MonsterSelectionDelegate?        // property for object conforming to MSDelegate

required init(coder aDecoder: NSCoder)      //      // coder because class is loaded from Storyboard
{
    super.init(coder: aDecoder)

    var dummyRecord1 = Record()
    dummyRecord1.details = "All was very good and strong with a little bit of lemon on the side of the hill."
    dummyRecord1.dateTimeEntered = NSDate(dateString: "2015-07-22")
    dummyRecord1.subject = "Clouds"
    dummyRecord1.locationEntered = "Drittelsgasse 1, 69493 Großsachsen, Germany."
    dummyRecord1.photos.append(UIImage(named: "zombies.jpg")!)

    records.append(dummyRecord1)
}

1 个答案:

答案 0 :(得分:2)

致电后

self.locationManager.requestWhenInUseAuthorization()

您无法立即开始更新位置。该调用是异步的。

以下是你应该如何正确地做到这一点:

1)检查授权状态:

switch CLLocationManager.authorizationStatus() {
    case .AuthorizedWhenInUse, .AuthorisedAlways:
        locationManager.startUpdatingLocation()
    case .NotDetermined:
        locationManager.requestWhenInUseAuthorization() // or request always if you need it
    case .Restricted, .Denied:
        // tell users that they need to enable access in settings
    default:
        break
}

2)如果您之前已经授权过您的应用,则应该更新位置。但是,如果您没有弹出窗口,则会出现。为了响应授权状态的变化,您需要添加另一个功能:

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if (status == .AuthorizedAlways) || (status == .AuthorizedWhenInUse) {
        locationManager.startUpdatingLocation()
    }
}