I need to get the geographical coordinates on Mac OS. Here is my code, but an error is reported when running: domain = kclerrordomain code = 0 "(null)"
import Cocoa
import CoreLocation
let locationManager:CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//设置定位服务管理器代理
locationManager.delegate = self
//设置定位进度
locationManager.desiredAccuracy = kCLLocationAccuracyBest //最佳定位
//更新距离
// locationManager.distanceFilter = 100
//发出授权请求
locationManager.requestAlwaysAuthorization()
if (CLLocationManager.locationServicesEnabled()){
//允许使用定位服务的话,开始定位服务更新
// print("定位开始")
}
}
extension ViewController:CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//获取最新的坐标
let currLocation : CLLocation = locations.last! // 持续更新
print("纬度:\(currLocation.coordinate.latitude) 纬度:\(currLocation.coordinate.longitude) 海拔:\(currLocation.altitude) 水平精度:\(currLocation.horizontalAccuracy) 垂直精度:\(currLocation.verticalAccuracy) 方向:\(currLocation.course) 速度:\(currLocation.speed)")
}
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
print("location manager auth status changed to:" )
switch status {
case .restricted:
print("status restricted")
case .denied:
print("status denied")
case .authorized:
print("已授权")
locationManager.startUpdatingLocation()
case .notDetermined:
print("status not yet determined")
default:
print("unknown state: \(status)")
}
}
func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
print( "location manager failed with error \(error)" )
}
}
enter image description here
When running application:
enter image description here
You need to add location usage description in your info.plist file. After adding your info.plist should look like this .
Add this line in viewDidLoad.
manager.startUpdatingLocation()
Then add the delegate method that updates the location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations.last?.coordinate)
}
Related
Below is my code. I am trying to have my map start off by being zoomed in to a certain number in xcode. It doesn't seem to work that way. Every time I open the map now, it's completely zoomed out to a point where you can see the entire continent. Any help will be much appreciated.
import UIKit
import MapKit
import CoreLocation
class YogaMap: UIViewController{
#IBOutlet weak var Yoga: MKMapView!
let locationManager = CLLocationManager()
let regionInMeters: Double = 100
override func viewDidLoad(){
super.viewDidLoad()
checkLocationServices()
}
func setupLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func centerViewOnUserLocation(){
if let location = locationManager.location?.coordinate{
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
Yoga.setRegion(region, animated: true)
}
}
func checkLocationServices(){
if CLLocationManager.locationServicesEnabled(){
setupLocationManager()
checkLocationAuthorization()
} else {
}
}
func checkLocationAuthorization(){
switch CLLocationManager.authorizationStatus(){
case .authorizedWhenInUse:
centerViewOnUserLocation()
break
case .denied:
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
break
case .restricted:
break
case .authorizedAlways:
break
}
}
}
extension YogaMap: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
}
}
Thanks
You should wait for location manager to return a location before trying to use centerViewOnUserLocation. Try moving your function call inside locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
You forgot call startUpdatingLocation in this function func setupLocationManager
func setupLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
Center map view when your location update
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
centerViewOnUserLocation()
}
I am making a weather app which gets temperature info by sending current coordinates. So I am using CLLocationManager. I haven't make any HTTP request yet. I would like to see "Location Unavailable" on my screen but it is not working.
I am following a tutorial and wrote exactly same code but in tutorial it is working. In debug session, it doesn't jump to didFailwithError or didUpdateLocations methods.I added all necessary things in my
info.plist and my phone's location services are open. According to my research locationManager.startUpdatingLocation() should call automatically
these methods but when I run my app nothing appears on UI.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("you got the location")
}
//Write the didFailWithError method here:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
cityLabel.text = "Location Unavaiable"
}
And
let locationManager = CLLocationManager ()
override func viewDidLoad() {
super.viewDidLoad()
//TODO:Set up the location manager here.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
You are updating location too soon, in fact before you get the permission from user.
After you ask for permission
locationManager.requestWhenInUseAuthorization()
Delegate method will call
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
}
Now its time to start updates. Guarding the status is a good idea since you don't want to start updating unless user permits it.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else { return }
manager.startUpdatingLocation()
}
Now you'll get location updates
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}
I am using Google maps SDK for iOS.
The isMyLocationEnabled is set to true.
Sometimes the use location updated to the right location. But sometimes the location is not updated.
I wanted to know if this option is using the original coordinates of the user? also, there is an option to update the user location? ) I am talking about the blue point.
May be this can help:
import Foundation
import CoreLocation
class Location: NSObject {
static let shared = Location()
var locationManager = CLLocationManager()
func locationManagerSetup() {
// Ask for Authorisation from the User.
locationManager.requestAlwaysAuthorization()
// If location services is enabled get the users location
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestLocation()
locationManager.startUpdatigLocation()
}
}
}
extension Location: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
// do something
manager.stopUpdatingLocation()
}
else {
manager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
manager.requestLocation()
}
// If we have been deined access give the user the option to change it
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if(status == CLAuthorizationStatus.denied) {
// do something
}
}
}
For some reason Xcode thinks I'm not implementing didFailWithError method of the CLLocationManagerDelegate protocol
I fail to see what I'm doing wrong, as I literally copied from another SO post that said this didFailWithErrormethod was updated for Swift 3. So I don't understand why Xcode thinks I'm not implementing didFailWithError
Any insight would be greatly appreciated!
Code
class OptionsViewController: UIViewController,
CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
override func viewDidLoad() {
//Ask user for location
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//Use users current location if no starting point set
if CLLocationManager.locationServicesEnabled() {
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse
|| CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways {
locationManager.requestLocation()
}
else{
locationManager.requestWhenInUseAuthorization()
}
}
else{
//Alert user to open location service, bra bra bra here...
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error:: \(error)")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("didChangeAuthorization")
if status == CLAuthorizationStatus.authorizedWhenInUse
|| status == CLAuthorizationStatus.authorizedAlways {
locationManager.requestLocation()
}
else{
//other procedures when location service is not permitted.
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did update location called")
// let locValue:CLLocationCoordinate2D = manager.location!.coordinate
// print("locations = \(locValue.latitude) \(locValue.longitude)")
if locations.first != nil {
print("location:: (location)")
}
}
Aaaandd I realized it's b/c I needed to use an Error of a specific type (specifically Swift.Error)
This is the right method declaration for didFailWithError:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Swift.Error) {
I want to use Background Fetch Location Updates service on my app. But don't show any output my codes here i want your help.
import CoreLocation
class ViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate {
var locationManager:CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
print("didChangeAuthorizationStatus")
switch status {
case .NotDetermined:
print(".NotDetermined")
break
case .Authorized:
print(".Authorized")
self.locationManager.startUpdatingLocation()
break
case .Denied:
print(".Denied")
break
default:
print("Unhandled authorization status")
break
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last as CLLocation!
print("didUpdateLocations: \(location.coordinate.latitude), \(location.coordinate.longitude)")
}
Giving output only
didChangeAuthorizationStatus
.NotDetermined
If it possible i want to take long lat value when new location changes.
Thank you !
I added this to the info.plist file:
<key>NSLocationAlwaysUsageDescription</key>
<string>Your message goes here</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your message goes here</string>