首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我有这样的错误:'locationManager‘的用法不明确

我有这样的错误:'locationManager‘的用法不明确
EN

Stack Overflow用户
提问于 2019-05-28 01:19:24
回答 1查看 375关注 0票数 1

我正在尝试在Swift 4中创建一个Geofence,但我遇到了一个问题,调用locationManager时出错,我不明白为什么会出现这个错误

这是错误:

locationManager的

用法不明确

我试图通过放置self.locationManager.startUpdatingLocation ()和其他不同的方法来纠正它,但都不起作用

在这里,我将变量声明为locationManager:

代码语言:javascript
复制
var locationManager = CLLocationManager()

    if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
      locationManager = appDelegate.locationManager
      locationManager.delegate = self
    }

下面是我收到错误的代码块:

代码语言:javascript
复制
if let locationManager = self.locationManager{
        let region = self.regionToMonitor()
        if(locationManager.monitoredRegions.count > 0){
            self.geofencesLabel.text = "Geofences OFF"
            locationManager.stopMonitoring(for: region)
            mapView.removeOverlays(mapView.overlays)
        }else{
            self.geofencesLabel.text = "Geofences ON"
            locationManager.startMonitoring(for: region)
            mapView.add(MKCircle(center: region.center, radius: region.radius))

            nombreU.isHidden = true
            empresaU.isHidden = true
            correoElectronicoU.isHidden = true
            telefonoU.isHidden = true

            //Generamos el registro en la base de datos local en el servidor
            let nombreEvento = self.nombreE
            let nombreOficial = self.nombreO
            let fechaEvento = self.fechaE
            let fechaFormato = self.fechaF
            let lugarEvento = self.lugarE
            let descripcionEvento = self.descripcionE
            let imagenEvento = self.imagenE
            let latitudEvento = self.latitudE
            let longitudEvento = self.longitudE
            let empresaEvento = self.empresaE
            let rolEvento = self.rolE

            //Recuperamos el contenido de las cajas de texto para validarlo
            let nombreC = self.nombreU.text!
            let empresaC = self.empresaU.text!
            let correoC = self.correoElectronicoU.text!
            let telefonoC = self.telefonoU.text!

            //Validamos que no este vacio ninguna de los datos recibidos del servidor y ninguna de las cajas de texto

            if(nombreC.isEmpty || empresaC.isEmpty || correoC.isEmpty || telefonoC.isEmpty){
                displayMyAlertMessage(userMessage: "Todos los campos deben ser llenados")
                return
            }

            if(nombreEvento.isEmpty || nombreOficial.isEmpty || fechaEvento.isEmpty || fechaFormato.isEmpty || lugarEvento.isEmpty || descripcionEvento.isEmpty){
                displayMyAlertMessage(userMessage: "Ocurrio un error al cargar los eventos")
                dismiss(animated: true, completion: nil)
                return
            }

            //Ingresamos los valores a la base de datos local
            let newEvento = NSEntityDescription.insertNewObject(forEntityName: "Eventos", into: context)
            newEvento.setValue(nombreEvento, forKey: "nombreE")
            newEvento.setValue(nombreOficial, forKey: "nombreO")
            newEvento.setValue(fechaEvento, forKey: "fechaE")
            newEvento.setValue(fechaFormato, forKey: "fechaF")
            newEvento.setValue(lugarEvento, forKey: "lugarE")
            newEvento.setValue(descripcionEvento, forKey: "descripcionE")
            newEvento.setValue(imagenEvento, forKey: "imagenE")
            newEvento.setValue(latitudEvento, forKey: "latitudE")
            newEvento.setValue(longitudEvento, forKey: "longitudE")
            newEvento.setValue(empresaEvento, forKey: "empresaE")
            newEvento.setValue(rolEvento, forKey: "rolE")

            nombreU.isHidden = true
            empresaU.isHidden = true
            correoElectronicoU.isHidden = true
            telefonoU.isHidden = true

            //Mostramos mensaje de que ya estas registrado
            mensajeRegistro.text = "Gracias por registrarte a nuestro evento"
            mensajeRegistro.isHidden = false


            do{
                try context.save()
                print("El registro al evento se realizo de forma correcta")
            }catch{
                print(error)
            }

            //Ejecutamos el codigo del WebService
            guard let url = URL(string: "http://www.sitioweb.mx/webservice/registro.php?nombre=\(nom)&empresa=\(empresaC)&correo=\(corC)&telefono=\(telC)") else { return }

            let session = URLSession.shared
            session.dataTask(with: url) { (data, response, error) in
                if let response = response {
                    print(response)
                }else{
                    print(error!)
                }
            }
        }

    }else{
        notify(msg: "El geofence no esta disponible")
    }

我的类有这个扩展名:

代码语言:javascript
复制
// MARK: - Location Manager Delegate
extension RegistroViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        mapView.showsUserLocation = status == .authorizedAlways
    }

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
        print("Monitoring failed for region with identifier: \(region!.identifier)")
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location Manager failed with the following error: \(error)")
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Location update")
    }

}

我不知道哪里出了问题,也不知道调用self.locationManager时应该引用什么方法

这是我的Appdelegate:

代码语言:javascript
复制
import UIKit
import CoreData
import CoreLocation
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    static var menu_bool = true
    static var menu_boolS = true

    let locationManager = CLLocationManager()


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        locationManager.delegate = self as? CLLocationManagerDelegate
        locationManager.requestAlwaysAuthorization()
        let options: UNAuthorizationOptions = [.badge, .sound, .alert]
        UNUserNotificationCenter.current().requestAuthorization(options: options){ success, error in
            if let error = error{
                print("Error: \(error)")
            }
        }
        return true
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-28 01:24:36

如果locationManager是实例属性,则直接使用它

代码语言:javascript
复制
let locationManager = CLLocationManager()

代码语言:javascript
复制
    let region = self.regionToMonitor()
    if(locationManager.monitoredRegions.count > 0){
        self.geofencesLabel.text = "Geofences OFF"
        locationManager.stopMonitoring(for: region)
        mapView.removeOverlays(mapView.overlays)
    }else{
        self.geofencesLabel.text = "Geofences ON"
        locationManager.startMonitoring(for: region)
        mapView.add(MKCircle(center: region.center, radius: region.radius))

不带

代码语言:javascript
复制
if let locationManager = self.locationManager{
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56330168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档