问题描述:

I'm working on apple watch app to retrieve user location. I have already import CoreLocation framework in to interfacecontroller class and added delegation to class. It does not work. Please check the code below. What am I missing?

 import Foundation

import WatchKit

import CoreLocation

class NearByController: WKInterfaceController, CLLocationManagerDelegate {

override func awakeWithContext(context: AnyObject?) {

var locationManager = CLLocationManager()

locationManager.delegate = self

locationManager.desiredAccuracy = kCLLocationAccuracyBest

locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {

locationManager.startUpdatingLocation()

}

}

// MARK: CLLocationManagerDelegate

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

println("Retrieved location")

}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {

println(error)

}

网友答案:

Seems like I need to initialise CLLocationManager as class attribute rather than inside method. Here is my answer. It is working now.

import Foundation
import WatchKit
import CoreLocation


class NearByController: WKInterfaceController, CLLocationManagerDelegate {


var locationManager = CLLocationManager()

override func awakeWithContext(context: AnyObject?) {

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
    }
}


// MARK: CLLocationManagerDelegate


func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    locationManager.stopUpdatingLocation()
    println(locations)
}



func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println(error)
}
相关阅读:
Top