2016-11-21 3 views
0

Делегат Методы CLLocationManagerделегат методы CLLocationManager не вызывался (Google Maps интегрирован)

didChangeAuthorizationStatus и didUpdateToLocation

не вызывался.

Location Always Usage Описание key уже добавлен в info.plist, и я получаю уведомление также, когда я запускаю приложение в первый раз.

Я могу видеть карту google, но я не могу видеть текущее местоположение. Когда я меняю местоположение, он не обновляется. Методы делегирования Basicaaly не вызываются.

// Код

import UIKit 
import GoogleMaps 

class ViewController: UIViewController,GMSMapViewDelegate { 
    @IBOutlet weak var mapViewTest: GMSMapView! 
    let locationManager = CLLocationManager() 
    var currentLocation :CLLocation = CLLocation(latitude: 0.0, longitude: 0.0) 
    var currentLatitude : Double = 0.0 
    var currentLongitude : Double = 0.0 
    override func viewDidLoad() 
    { 
     super.viewDidLoad()`` 
     locationManager.delegate = self 
     if (CLLocationManager.locationServicesEnabled()) 
     { 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.allowsBackgroundLocationUpdates = true 
     locationManager.requestAlwaysAuthorization() 
     locationManager.startUpdatingLocation() 
     } 
     // Do any additional setup after loading the view, typically from a nib. 
    } 
} 


    extension ViewController : CLLocationManagerDelegate 
    { 
     func locationManager(manager: CLLocationManager,  didChangeAuthorizationStatus status: CLAuthorizationStatus) 
     { 
      if status == .authorizedAlways 
      { 
       if(CLLocationManager .locationServicesEnabled()) 
       { 
        locationManager.startUpdatingLocation() 
        mapViewTest.isMyLocationEnabled = true 
        mapViewTest.settings.myLocationButton = true 
       } 
      } 
     } 
     func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) 
     { 
      mapViewTest.camera = GMSCameraPosition(target: (newLocation.coordinate), zoom: 15, bearing: 0, viewingAngle: 0) 
      currentLocation = newLocation 
      currentLatitude = newLocation.coordinate.latitude 
      currentLongitude = newLocation.coordinate.longitude 

     } 
     func locationManager(manager: CLLocationManager, didFailWithError error: NSError) 
     { 
      print("Errors: " + error.localizedDescription) 
     } 
    } 
+0

Установить точку останова в 'locationManager.startUpdatingLocation()' называется ли это? – shallowThought

ответ

3

Из кода вы работаете с Swift 3, и в Swift подписи 3 CLLocationManagerDelegate метода изменяется как это.

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { 

} 

//func locationManager(_ manager: CLLocationManager, didUpdateTo newLocation: CLLocation, 
     from oldLocation: CLLocation) is deprecated with below one 
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

} 

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

} 

Проверить Apple, Документация по CLLocationManagerDelegate для более подробной информации.

+0

Это тоже решило мою проблему. – vrao

0

Добавьте эти два свойства в вашем info.plist

NSLocationWhenInUseUsageDescription 
NSLocationAlwaysUsageDescription 
+0

Они уже были добавлены, все еще столкнувшись с проблемой. –

+0

@narayanaMV Вы уже исправились? Я сейчас работаю в той же проблеме .... :-( –

2

После проверки коды я нашел некоторые изменения, необходимые, чтобы сделать как следует,

примечания: Я только добавил код, имеющие проблемы здесь менеджер местонахождения

import UIKit 
import CoreLocation 

class ViewController: UIViewController { 

    let locationManager = CLLocationManager() 

    var currentLocation :CLLocation = CLLocation(latitude: 0.0, longitude: 0.0) 
    var currentLatitude : Double = 0.0 
    var currentLongitude : Double = 0.0 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     locationManager.delegate = self 
     if (CLLocationManager.locationServicesEnabled()) 
     { 
      locationManager.desiredAccuracy = kCLLocationAccuracyBest 
      locationManager.allowsBackgroundLocationUpdates = true 
      locationManager.requestAlwaysAuthorization() 
      locationManager.startUpdatingLocation() 
     } 
    } 

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

} 

extension ViewController : CLLocationManagerDelegate { 

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

    } 

    func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) { 
     print("Errors: " + (error?.localizedDescription)!) 
    } 
} 

Кроме того, добавьте ниже строк в .plist файл, если не добавлен,

<key>NSLocationWhenInUseUsageDescription</key> 
    <string>$(PRODUCT_NAME) location use</string> 
    <key>NSLocationAlwaysUsageDescription</key> 
    <string>$(PRODUCT_NAME) always uses location </string> 
0

вам нужно поставить делегата mapview в себя.

попробовать это:

override func viewDidLoad() { 
    super.viewDidLoad() 

    // User Location Settings 
    locationManager.delegate = self 
    locationManager.requestWhenInUseAuthorization() 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager.startUpdatingLocation() 

    // Google Maps Delegate 
    mapView.delegate = self 
} 

// View will appear 
override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 

    // Google maps settings 
    mapView.isMyLocationEnabled = true 
    mapView.settings.myLocationButton = true 

    // Get location if autorized 
    if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse) { 
     let (latitude, longitude) = self.getLocation() 
     mapView.camera = GMSCameraPosition.camera(
      withLatitude: latitude, 
      longitude: longitude, 
      zoom: 14) 
    } 
} 


    //Get the user location 
    func getLocation() -> (latitude: CLLocationDegrees, longitude: CLLocationDegrees) { 

    let latitude = (locationManager.location?.coordinate.latitude)! 
    let longitude = (locationManager.location?.coordinate.longitude)! 

    return (latitude, longitude) 
} 
Смежные вопросы