J86*_*J86 2 coordinates cllocationmanager ios swift
我正在使用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)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的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()
}
Run Code Online (Sandbox Code Playgroud)
以上不起作用.我的didUpdateLocations代表永远不会被召唤.而在调试控制台/输出我总是No Location :(打印出来,这表明在获得位置的失败,更具体的提示上的位置属性我AppDelegate是nil.
我为解决这个问题所做的一切:
NSLocationWhenInUseUsageDescription和NSLocationAlwaysUsageDescription无数其他代码调整,仍然没有.
几点意见:
正如你所指出的那样,如果你打算打电话requestAlwaysAuthorization,那么你必须设置NSLocationAlwaysUsageDescription.如果你打电话requestWhenInUseAuthorization,你需要NSLocationWhenInUseUsageDescription.(您看到确认对话框的事实意味着您已正确完成此操作.我假设您正在查看您在确认警报中提供的任何描述.)
在您的模拟器上,您可能无法在设备上看到位置更新.在实际设备上测试.
当我使用你的代码时,我看到didUpdateLocations我从一个设备调用它,而不是从模拟器调用.
一旦解决了看不到didUpdateLocations被叫的问题,就会出现另一个问题:
您在授权状态更改时发布通知,但不是在异步接收位置时(即稍后).坦率地说,从视图控制器的角度来看,后者是更重要的事件,所以我认为(a)你应该在收到位置时发布通知; (b)视图控制者应遵守此通知.现在,即使你成功didUpdateLocations被调用,视图控制器也不会被通知.
此外,您didUpdateLocations正在启动另一个异步过程,即坐标的地理编码.如果您的视图控制器也需要,您应该在地理编码器的完成块内发布通知.
坦率地说,您甚至没有向我们展示视图控制器代码,该CLLocationManagerDelegate代码为此代码将调用的任何通知添加观察者,但我假设您已经这样做了.
| 归档时间: |
|
| 查看次数: |
11557 次 |
| 最近记录: |