新手Swift家伙在这里-我曾在viewcontroller类中完美运行过定位服务,但是我意识到它在逻辑上位于较早的view controller类中,并将其移到了这里,但是从那时起,位置服务就被完全跳过了,只运行了seque 。我已经检查了明显的内容(文件检查器中列出了viewcontroller)。
import UIKit
import CoreLocation
var userLat = Double()
var userLong = Double()
class FirstViewController: UIViewController, CLLocationManagerDelegate {
//instantiate location manager
var locationManager = CLLocationManager()
//get location data
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
//start updating location
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
//get coordinates
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
//check to see if user has allowed app to see location and use those lats if is the case
if CLLocationManager.locationServicesEnabled() {
userLat = userLocation.coordinate.latitude
userLong = userLocation.coordinate.longitude
}
//check if you got any data?
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
//stop updating location
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
//perform Seques
@IBAction func CheckLocation(_ sender: Any) {
//cecking if user location is enableded?
if CLLocationManager.locationServicesEnabled(){
performSegue(withIdentifier: "two", sender: self)
}
else{
performSegue(withIdentifier: "three", sender: self)
}
}
@IBAction func Locatiohn(_ sender: Any) {
performSegue(withIdentifier: "three", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "sun.jpg")!)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
//override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
答案 0 :(得分:0)
我通过从以下代码中添加删除的“ func”并将其放置在viewDidLoad中来解决了此问题。\
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
//start updating location
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}