我正在学习使用 Swift 开发 iOS 8 应用程序。我遵循了关于 Treehouse 的教程它将引导您在 Swift 和 iOS 8 中构建一个天气应用程序。
作为对应用程序的改进,作者/导师建议使用 CLLocationManager 获取设备的位置以输入天气 API,而不是硬编码的纬度和经度值。
因此,在阅读了各种在线教程后,我继续尝试实现这个建议的改进。
我已将负责获取位置坐标的代码放在 AppDelegate.swift 文件中。
AppDelegate.swift代码
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var locationManager: CLLocationManager!
var errorOccured: Bool = false
var foundLocation: Bool = false
var locationStatus: NSString = "Not Started"
var location: CLLocationCoordinate2D?
var locationName: String?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.setStatusBarHidden(true, withAnimation: .None)
initializeLocationManager()
return true
}
func initializeLocationManager() {
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("didUpdateLocations running")
if (foundLocation == false) {
self.locationManager.stopUpdatingLocation()
foundLocation = true
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
var geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(locationObj, completionHandler: { (placemarks, error) -> Void in
var p = placemarks as NSArray
var placemark: CLPlacemark? = p.lastObject as? CLPlacemark
self.locationName = placemark?.name
})
self.location = locationObj.coordinate
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if ((error) != nil) {
if (errorOccured == false) {
errorOccured = true
print(error)
}
}
}
// authorization status
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
locationManager.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}
}
然后在我的 ViewController.swift 文件中,我想获取位置坐标。这是代码:
ViewController.swift代码
func getCurrentWeatherData() -> Void {
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
var forecastURL: NSURL
var locName = "London"
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.foundLocation = false
if let loc = appDelegate.location {
println("Got Location!") // for debug purposes
var currentLat = loc.latitude
var currentLng = loc.longitude
forecastURL = NSURL(string: "\(currentLat),\(currentLng)", relativeToURL: baseURL)
locName = appDelegate.locationName!
} else {
println("No Location :(") // for debug purposes
var currentLat = "51.513445"
var currentLng = "-0.157828"
forecastURL = NSURL(string: "\(currentLat),\(currentLng)", relativeToURL: baseURL)
}
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
var urlContents = NSString.stringWithContentsOfURL(location, encoding: NSUTF8StringEncoding, error: nil)
if (error == nil) {
let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject, options: nil, error: nil) as NSDictionary
let currentWeather = Current(weatherDictionary: weatherDictionary)
dispatch_async(dispatch_get_main_queue(), {
() -> Void in
self.locationNameLabel.text = "\(locName)"
self.temperatureLabel.text = "\(currentWeather.temperature)"
self.iconView.image = currentWeather.icon!
self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
self.humidityLabel.text = "\(currentWeather.humidity)"
self.percipitationLabel.text = "\(currentWeather.percipProbability)"
self.summaryLabel.text = "\(currentWeather.summary)"
// Stop refresh animation
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
} else {
let networkIssueController = UIAlertController(title: "Error", message: "Unable to load data. Connectivity error!", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
networkIssueController.addAction(okButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: nil)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
}
})
downloadTask.resume()
}
以上是不工作。我的 didUpdateLocations 委托(delegate)从未被调用。在调试控制台/输出中,我总是打印出 No Location :(,这表明获取位置失败,更具体地说,我的 AppDelegate 上的位置属性是无。
我为解决这个问题所做的事情:
NSLocationWhenInUseUsageDescription 和 NSLocationAlwaysUsageDescription还有无数其他代码调整,但仍然一无所获。
最佳答案
一些观察:
正如您所指出的,如果您要调用 requestAlwaysAuthorization,则必须设置 NSLocationAlwaysUsageDescription。如果您调用了 requestWhenInUseAuthorization,则需要 NSLocationWhenInUseUsageDescription。 (您看到确认对话框的事实意味着您已正确完成此操作。我假设您看到的是您在确认警报中提供的任何描述。)
在您的模拟器上,您可能无法像在设备上那样看到位置更新。在实际设备上进行测试。
当我使用您的代码时,当我从设备而不是模拟器调用它时,我看到 didUpdateLocations。
一旦解决了看不到 didUpdateLocations 被调用的问题,还有另一个问题:
您在授权状态更改时发布通知,而不是在异步接收位置时(即稍后)。坦率地说,从 View Controller 的角度来看,后者是更关键的事件,所以我认为(a)你应该在收到位置时发布通知; (b) View Controller 应该观察这个通知。现在,即使您成功调用了 didUpdateLocations,也不会通知 View Controller 。
此外,您的 didUpdateLocations 正在启动另一个异步过程,即坐标的地理编码。如果您的 View Controller 也需要它,您应该在地理编码器的完成 block 内发布通知。
坦率地说,您甚至没有向我们展示添加观察者的 View Controller 代码,以观察此 CLLocationManagerDelegate 代码将调用的任何通知,但我假设您已经这样做了。
关于ios - CLLocationManager didUpdateLocations 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201471/