cloudy45man
cloudy45man

Reputation: 391

CLLocationManagerDelegate method not working on apple watch extension

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)
}

Upvotes: 0

Views: 597

Answers (1)

cloudy45man
cloudy45man

Reputation: 391

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)
}

Upvotes: 1

Related Questions