【发布时间】:2015-09-17 18:21:36
【问题描述】:
我有两个不同的类,其中之一是 LocationService,仅用于确定位置。问题是我不知道为什么它不更新坐标变量。
视图控制器:
import UIKit
class ViewController: UIViewController {
var coords: (lat: Double, long: Double) = (0,0)
var tracking = LocationServices()
override func viewDidLoad() {
super.viewDidLoad()
tracking.startTracking()
tracking.getLocations()
coordinat = tracking.coordinates
retreiveWeatherForecast()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// retrieveWeatherForecast functions
还有简单的locationService类:
import UIKit
import CoreLocation
class LocationServices: NSObject, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var coordinates: (lat: Double, long: Double) = (0,0)
func startTracking() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
locationManager.stopUpdatingLocation()
print(error)
}
func getLocations() {
#if os (ios)
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
//println("locations = \(locationManager)")
var latValue = locationManager.location.coordinate.latitude
var lonValue = locationManager.location.coordinate.longitude
coordinates = (latValue,lonValue)
println(latValue)
println(lonValue)
}
#endif
}
}
当我构建它时,它会返回默认坐标 = (0,0) 的天气。
【问题讨论】:
-
你为什么把 didUpdateLocations 方法放在 getLocations() 下?
-
在实际启动retrieveWeatherForecast 函数之前,我试图让它工作(初始化)。
-
你在 plist 文件中添加了
NSLocationAlwaysUsageDescription吗? -
@Shoaib,您是否使用 DELEGATES 删除了您的解决方案?到处都找不到。我需要在 DidUpdateLocations 函数之后让它的 retrieveWeather 函数工作。
标签: ios swift core-location cllocationmanager