我正在使用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
代表从未被调用过。在调试控制台/输出中,我总是打印出No Location :(
,表示获取位置失败,更具体地说明我的AppDelegate
上的位置属性为nil
。
我采取了一些措施来解决这个问题:
NSLocationWhenInUseUsageDescription
和NSLocationAlwaysUsageDescription
无数其他代码调整,但仍然没有。
答案 0 :(得分:7)
有几点意见:
正如您所指出的,如果您要致电requestAlwaysAuthorization
,则必须设置NSLocationAlwaysUsageDescription
。如果您致电requestWhenInUseAuthorization
,则需要NSLocationWhenInUseUsageDescription
。 (您看到确认对话框意味着您已正确完成此操作。我假设您在确认提醒中看到了您提供的任何描述。)
在您的模拟器上,您可能无法在设备上看到位置更新。在实际设备上测试。
当我使用您的代码时,当我从设备调用此代码时,我会看到didUpdateLocations
,但不是来自模拟器。
一旦解决了未看到didUpdateLocations
的问题,就会出现另一个问题:
您在授权状态更改时发布通知,但不是在异步接收位置时(即稍后)。坦率地说,从视图控制器的角度来看,后者是更重要的事件,所以我认为(a)你应该在收到位置时发布通知; (b)视图控制者应遵守此通知。现在,即使您成功调用didUpdateLocations
,视图控制器也不会收到通知。
此外,您的didUpdateLocations
正在启动另一个异步过程,即坐标的地理编码。如果您的视图控制器也需要它,您应该在地理编码器的完成块内发布通知。
坦率地说,您甚至没有向我们展示视图控制器代码,该代码为此CLLocationManagerDelegate
代码将调用的任何通知添加观察者,但我认为您已经这样做了。
答案 1 :(得分:3)
仅供记录:我首先将两个键(NSLocationAlwaysUsageDescription
和NSLocationWhenInUseUsageDescription
)放入test-plist
而不是application-plist
。我花了一些时间才意识到.....