Sam VG
Sam VG

Reputation: 163

Delegate must respond to locationManager:didUpdateLocations swift eroor

Hy guys, I'm making an app in swift 3.0 but I ran across a problem pretty soon. I set up necessary functions to ask for permission to use a location but every time I run the app I get the same error...

Viewcontroller.h

import UIKit
import MapKit

class ViewController: UIViewController {

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

extension ViewController : CLLocationManagerDelegate {
    private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
        }
    }

    private func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if locations.first != nil {
            print("location:: (location)")
        }
    }

    private func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("error:: (error)")
    }
}

Error:

2016-10-31 16:12:11.436192 Assemble[57741:2743477] bundleid: com.AssembleTm.Assemble, enable_level: 0, persist_level: 0, propagate_with_activity: 0
2016-10-31 16:12:11.437006 Assemble[57741:2743477] subsystem: com.apple.siri, category: Intents, enable_level: 1, persist_level: 1, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0
2016-10-31 16:12:11.524494 Assemble[57741:2743668] subsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-10-31 16:12:11.526709 Assemble[57741:2743668] subsystem: com.apple.UIKit, category: HIDEventIncoming, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-10-31 16:12:11.561488 Assemble[57741:2743658] subsystem: com.apple.BaseBoard, category: MachPort, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0
2016-10-31 16:12:11.638717 Assemble[57741:2743477] subsystem: com.apple.UIKit, category: StatusBar, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0
2016-10-31 16:12:11.744 Assemble[57741:2743477] *** Assertion failure in -[CLLocationManager requestLocation], /BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreLocationFramework_Sim/CoreLocation-2100.0.12/Framework/CoreLocation/CLLocationManager.m:865
2016-10-31 16:12:11.855 Assemble[57741:2743477] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didUpdateLocations:'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010a58d34b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010873b21e objc_exception_throw + 48
    2   CoreFoundation                      0x000000010a591442 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x0000000106799edd -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
    4   CoreLocation                        0x0000000106291523 CLClientGetCapabilities + 13233
    5   Assemble                            0x00000001061e1976 _TFC8Assemble14ViewController11viewDidLoadfT_T_ + 294
    6   Assemble                            0x00000001061e19e2 _TToFC8Assemble14ViewController11viewDidLoadfT_T_ + 34
    7   UIKit                               0x000000010708f06d -[UIViewController loadViewIfRequired] + 1258
    8   UIKit                               0x000000010708f4a0 -[UIViewController view] + 27
    9   UIKit                               0x0000000106f59045 -[UIWindow addRootViewControllerViewIfPossible] + 71
    10  UIKit                               0x0000000106f59796 -[UIWindow _setHidden:forced:] + 293
    11  UIKit                               0x0000000106f6d0a9 -[UIWindow makeKeyAndVisible] + 42
    12  UIKit                               0x0000000106ee6259 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4818
    13  UIKit                               0x0000000106eec3b9 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1731
    14  UIKit                               0x0000000106ee9539 -[UIApplication workspaceDidEndTransaction:] + 188
    15  FrontBoardServices                  0x000000010e1cf76b __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    16  FrontBoardServices                  0x000000010e1cf5e4 -[FBSSerialQueue _performNext] + 189
    17  FrontBoardServices                  0x000000010e1cf96d -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    18  CoreFoundation                      0x000000010a532311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    19  CoreFoundation                      0x000000010a51759c __CFRunLoopDoSources0 + 556
    20  CoreFoundation                      0x000000010a516a86 __CFRunLoopRun + 918
    21  CoreFoundation                      0x000000010a516494 CFRunLoopRunSpecific + 420
    22  UIKit                               0x0000000106ee7db6 -[UIApplication _run] + 434
    23  UIKit                               0x0000000106eedf34 UIApplicationMain + 159
    24  Assemble                            0x00000001061e3fcf main + 111
    25  libdyld.dylib                       0x000000010af5b68d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

I'm new to swift 3.0 but I couldn't find anything on how to solve this (I alreaddy looked it up on stackoverflow but the answer they gave didn't help me...)

Upvotes: 14

Views: 22652

Answers (8)

Musa Kazim
Musa Kazim

Reputation: 25

I forgot to put locationManager.delegate = self in viewDidLoad(), after adding it, the issue got solved

Upvotes: -1

222_Aswin V.B
222_Aswin V.B

Reputation: 1

Tried all the methods above. And found that the below 2 steps are required for this to work

  1. Setting the delegate property to self
    locationManager.delegate = self

  2. Adding the didFailWithError delegate method even if there was no specific implementation required
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed") }

Upvotes: -1

Mahmoud Eldesouky
Mahmoud Eldesouky

Reputation: 769

As mentioned in this answer, your problem could be like mine, having your own Error class that conflicts with Swift.Error

func locationManager(_ manager: CLLocationManager, didFailWithError error: Swift.Error) {

Upvotes: 0

Quick learner
Quick learner

Reputation: 11467

This worked for me

import UIKit
import CoreLocation

class WeatherViewController: UIViewController {
    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var searchInputField: UITextField!
    var weatherManager = WeatherManager()
    var locationManager=CLLocationManager()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchInputField.delegate=self
        weatherManager.delegate=self
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
        // Do any additional setup after loading the view.
    }
 
}
extension WeatherViewController : CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
         print("error:: \(error.localizedDescription)")
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if locations.first != nil {
            print("location:: \(locations[0])")
        }

    }

}

Upvotes: 0

Teja Goud Kandula
Teja Goud Kandula

Reputation: 1574

import UIKit
import CoreLocation

class ViewController: UIViewController {
    
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        
        super.viewDidLoad()

        locationManager.delegate = self        
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestLocation()
    }
}

extension ViewController : CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            print("Location data received.")
            print(location)
        }
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Failed to get users location.")
    }
}

The delegate needs to be assigned before calling the requestLocation() function because after the requestLocation() is completed it will trigger didUpdateLocations, but to call didUpdateLocations it should know which object didUpdateLocations is being called. To clarify that to the compiler
locationManager.delegate = self is used to before the locationManager.requestLocation() call is made.

In the extension of CLLocationManagerDelegate protocol implement didUpdateLocations and didFailWithError.

Upvotes: 6

Marques
Marques

Reputation: 1914

Another possible cause of error is that you only have the method for

locationManager(_:didUpdateLocations:)

and you are missing the method for

locationManager(_:didFailWithError:)

According to the documentation of requestLocation():

When using this method, the associated delegate must implement the locationManager(:didUpdateLocations:) and locationManager(:didFailWithError:) methods. Failure to do so is a programmer error.

Upvotes: 6

rockdaswift
rockdaswift

Reputation: 9983

It's possible to get this error if you request the location to the location manager and it's delegate is nil. Make sure that you always set the delegate before calling to any location request.

For example, set the delegate first:

locationManager.delegate = self

Before requesting the location:

locationManager.requestLocation()

Upvotes: 23

LC 웃
LC 웃

Reputation: 18998

You are using xcode8 and swift3 but your delegate methods are copied from swift 2.Change your delegate methods as below.

extension ViewController : CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
         print("error:: \(error.localizedDescription)")
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if locations.first != nil {
            print("location:: (location)")
        }

    }

}

Upvotes: 25

Related Questions