Googlemaps не позволяет мне найти местоположение пользователей? - PullRequest
0 голосов
/ 12 июня 2018

Я пытаюсь создать контроллер представления на swift, который показывает, где находится пользователь.Я уже реализовал Google Maps, поэтому теперь все, что мне нужно сделать, это подключить правильный код.При этом я продолжаю получать эти два сообщения об ошибках, а затем приложение вылетает.Может ли кто-нибудь помочь мне с поиском решения> любая помощь приветствуется.

import UIKit
import Foundation
import Firebase
import MapKit
import GoogleMaps
import CoreLocation

class mainViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    let defaults = UserDefaults.standard
    let locationManager = CLLocationManager()
    var mapView = GMSMapView()
    var camera = GMSCameraPosition()


    override func viewDidLoad() {
        super.viewDidLoad()

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

        GMSServices.provideAPIKey("AIzaSyBDOLisA3c-wDTbkbSssAxEb3iLw7Y5vHo")

        let camera = GMSCameraPosition.camera(withLatitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.latitude)!, zoom: 17)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        view = mapView

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.latitude)!)
        marker.snippet = "Current Location"
        marker.map = mapView
        self.mapView.addSubview(mapView)

        view.backgroundColor = GREEN_Theme
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = "Welcome"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(Logout))
        }
    @objc func Logout() {
        print("Logged Out")
        do {

// I am receiving this error message on the auth.auth().signOut() "Use of unresolved identifier 'Auth'"
            try  Auth.auth().signOut()
            defaults.set(false, forKey: "user is logged in")
            let loginController = UINavigationController(rootViewController: LoginController())
            present(loginController, animated: true, completion: nil)
        } catch let err {
            print(err.localizedDescription)
        }

    }
}

Ответы [ 2 ]

0 голосов
/ 14 июня 2018

Вы используете Google Map в качестве вида карты, что означает, что вы создаете экземпляр класса GMSMapView.Это объект.У тебя есть.И я предполагаю, что это IBOutlet-проводной.Он поставляется с несколькими методами делегатов.Таким образом, вы можете установить его делегат.И вы хотите, чтобы ваш контроллер представления получал данные из GMSMapView.Таким образом, вы устанавливаете делегата этого класса на себя (ваш контроллер представления).

import UIKit
import Foundation
import Firebase
import GoogleMaps
import CoreLocation

class mainViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
    // MARK: - Instance variables
    private let locationManager = CLLocationManager()

    // MARK: - IBOutlets
    @IBOutlet weak var mapView: GMSMapView!

    // MARK: - IBActions

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self
        mapView.isMyLocationEnabled = true
    }
    // MARK: - Life cycle


    // MARK: - GMSMapView delegate methods
    func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
        reverseGeocodeCoordinate(position.target) // sending data when the mapView is not moved or pinched by the finger //
    }

    func reverseGeocodeCoordinate(_ coordinate: CLLocationCoordinate2D) {
        let geocoder = GMSGeocoder()
        geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
            guard let address = response?.firstResult(), let lines = address.lines else {
                return
            }

            ...
            ...
        }
    }
}
0 голосов
/ 14 июня 2018

Ваша проблема в том, что CLLocationManager не имеет достаточно времени для извлечения информации, и в то же время другие функции запрашивают эту информацию, которая все еще равна нулю.

Приведенный ниже вопрос решит проблему, он также прекращает постоянно обновлять местоположения, которые могут разрядить батарею, особенно если учесть, что вы установили AccuracyBest.

func getLocation(){
    locationManager=CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
    let lastLocation=locations[locations.count-1]
    if lastLocation.horizontalAccuracy>0{
        locationManager.stopUpdatingLocation()
        let latitude = lastLocation.coordinate.latitude
        let longitude = lastLocation.coordinate.longitude

        GMSServices.provideAPIKey("AIzaSyBDOLisA3c-wDTbkbSssAxEb3iLw7Y5vHo")
// everything that is going to require the latitude and longitude from the location manager goes here
        let camera = GMSCameraPosition.camera(withLatitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.latitude)!, zoom: 17)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        self.view = mapView

        let marker = GMSMarker()
         marker.position = CLLocationCoordinate2D(latitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.latitude)!)
         marker.snippet = "Current Location"
         marker.map = mapView
         self.mapView.addSubview(mapView)
      }
 }

Ваш viewDidLoad должениметь:

 override func viewDidLoad() {
    super.viewDidLoad()

    getLocation()

    view.backgroundColor = GREEN_Theme
    navigationController?.navigationBar.prefersLargeTitles = true
    navigationItem.title = "Welcome"
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(Logout))
    } 
...