您好我正在创建一个获取用户位置的程序,并在地图上添加相应的注释。我开始编写View Controller中的所有代码,它完美地获取了位置。下面是视图控制器中的工作代码。
class MapViewController: UIViewController, CLLocationManagerDelegate {
var annotation = MKPointAnnotation()
var userLocation: CLLocation?
@IBOutlet weak var mapView: MKMapView!
var locationManager:CLLocationManager!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineCurrentLocation()
}
func determineCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
print("user latitude = \(userLocation?.coordinate.latitude)")
print("user longitude = \(userLocation?.coordinate.longitude)")
annotation.coordinate = CLLocationCoordinate2D(latitude: (userLocation?.coordinate.latitude)!, longitude: (userLocation?.coordinate.longitude)!)
annotation.title = "You"
mapView.addAnnotation(annotation)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
但是现在我尝试在另一个swift文件中重新创建几乎完全相同的代码。 didUpdateLocations永远不会被调用。 locationManager.startUpdatingLocation()确实被调用。
下面是我从View Controller调用的新swift文件。我在这里缺少任何简单的概念,因为我真的不明白为什么这不起作用。
import Foundation
import CoreLocation
class SendLocation: NSObject, CLLocationManagerDelegate {
var userLocation: CLLocation?
var locationManager:CLLocationManager!
func sendLocationPost() {
determineCurrentLocation()
}
func determineCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
print("WHY")
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
print("user latitude = \(userLocation?.coordinate.latitude)")
print("user longitude = \(userLocation?.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
}
我用它来打电话:
let location = SendLocation()
location.sendLocationPost()`
在我的View Controller中
答案 0 :(得分:0)
发生这种情况是因为您没有保留对SendLocation对象的引用。
使SendLocation成为UIViewController的属性。
例如,从静态范围调用它不会保留引用。
WONT WORK:
static func sendLocation() {
let location = SendLocation()
location.sendLocationPost()
}
将工作
let location = SendLocation()
func sendLocation() {
location.sendLocationPost()
}