Xcode Swift-当前位置的自有结构/类(CLLocationManager)

Xcode Swift-当前位置的自有结构/类(CLLocationManager),xcode,swift,struct,location,cllocationmanager,Xcode,Swift,Struct,Location,Cllocationmanager,我想创建一个自己的结构或类来获取用户的当前位置 似乎我无法在结构中使用CLLocationManager及其函数(didUpdateLocations、didFailWithError等)(Xcode使所有文本颜色变为黑色,我收到一个错误,说发生了内部错误。源代码编辑器有限。)。当我使用一个类并尝试使用“getPlacemark”-函数(从实例类获取placemark)或直接从创建的实例(“InstanceClass.placemarkInClass”)获取它时,但没有任何效果,我只获得线程1:

我想创建一个自己的结构或类来获取用户的当前位置

似乎我无法在结构中使用CLLocationManager及其函数(didUpdateLocations、didFailWithError等)(Xcode使所有文本颜色变为黑色,我收到一个错误,说发生了内部错误。源代码编辑器有限。)。当我使用一个类并尝试使用“getPlacemark”-函数(从实例类获取placemark)或直接从创建的实例(“InstanceClass.placemarkInClass”)获取它时,但没有任何效果,我只获得
线程1:EXC\u BAD\u访问

这是我创建类的最后一次尝试:

import Foundation
import MapKit

class UserLocation: NSObject, CLLocationManagerDelegate{

    var mLocationManager: CLLocationManager
    var placemark: CLPlacemark

    override init(){
        placemark = CLPlacemark()
        self.mLocationManager = CLLocationManager()
        self.mLocationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.mLocationManager.requestWhenInUseAuthorization()
        self.mLocationManager.startUpdatingLocation()
    }

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

        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error) -> Void in

            if (error != nil) {
                print("Error: " + (error?.localizedDescription)!)
                return
            }
            if (placemarks?.count > 0) {
                let pm = placemarks![0]
                self.placemark = pm
                print(self.placemark.areasOfInterest)
                self.mLocationManager.stopUpdatingLocation()
            }

        })

    }

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

    func getPlacemark() -> CLPlacemark{
        return self.placemark
    }

}
在我的ViewController中,我将其设置为实例变量(currentLocation=currentLocation()),并尝试同时使用这两个变量

让userPlacemark=currentLocation.getPlacemark() 和 让userPlacemark=currentLocation.placemark 但一切都不起作用


有没有办法拥有自己的类或结构来获取当前位置并在其他ViewController中使用它?

代码中有两个观察结果:

  • 一旦完成成员变量的设置,就不能在init中调用[super init]。将您的init修改为

         init(){
    
           placemark = CLPlacemark()
    
            mLocationManager = CLLocationManager()
            mLocationManager.desiredAccuracy = kCLLocationAccuracyBest
            mLocationManager.requestWhenInUseAuthorization()
            mLocationManager.startUpdatingLocation()
            super.init()
            mLocationManager.delegate = self
           }
    
  • 设置位置管理器的委派。您应该在创建location manager实例后不久在init中执行此操作。请参阅上面的init代码

  • 当我使用它时,我会在super.init调用之前使用“self”。但问题是我无法接收位置。当我尝试使用getPlacemark方法时,没有设置位置。我试过用,但没用。我想创建一个这样的类。我似乎找不到任何能给我答案的教程或帖子。