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