Reputation: 1662
I have a view controller which hase these functions:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
print("loc")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError){
if(error.code == CLError.Denied.rawValue){
print("error")
}
}
It is direct child of this class:
import UIKit
import CoreLocation
class UIViewLocationManager : UIViewController, CLLocationManagerDelegate{
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
print(status.rawValue)
switch status {
case .NotDetermined:
break
case .AuthorizedWhenInUse:
if #available(iOS 9.0, *) {
manager.requestLocation()
} else {
manager.startUpdatingLocation()
}
break
case .AuthorizedAlways:
break
case .Denied:
break
default:
break
}
}
}
And then I have this class
class CoreLocationController : NSObject {
func requestLocationUpdate(delegate : CLLocationManagerDelegate){
let locationManager = CLLocationManager()
locationManager.delegate = delegate
if #available(iOS 8.0, *) {
locationManager.requestWhenInUseAuthorization()
} else {
locationManager.startUpdatingLocation()
}
then in AppDelegate I declare it like:
let coreLocationController = CoreLocationController()
But when I call requestLocationUpdate(self)
from viewController which is child of UIViewLocationManager
I dont receive any updates. However if I just copy-paste all methods to CoreLocationController
and I do locationManager.delegate = self
in CoreLocationController init()
method than everything works fine.
Any ideas? I am really desperate because I have already tried so much aproaches but still cant get this working.
Thanks in advance
Upvotes: 0
Views: 310
Reputation: 6806
locationManager
is a local variable within the requestLocationUpdate
method. At the end of the call to requestLocationUpdate
, locationManager
will be destroyed and the CLLocationManager
just created will have nothing referencing it, so it will be destroyed too, despite the fact that you have asked it to send messages to an extant delegate
.
If the instance of CoreLocationController
you have created is not destroyed - something always points to the instance - then changing locationManager
to an instance variable should fix this:
class CoreLocationController : NSObject {
var locationManager:CLLocationManager?
func requestLocationUpdate(delegate : CLLocationManagerDelegate) {
locationManager = CLLocationManager()
locationManager?.delegate = delegate
locationManager?.requestWhenInUseAuthorization()
}
}
The above code is working for me in a real iPhone 5 and in a simulated iPhone 6. The location update delegate code gets called. I did have to edit the plist as specified in CLLocation Manager in Swift to get Location of User
Upvotes: 1