SWIFT:核心位置返回nil - 如何调用didUpdateLocations?

时间:2016-06-21 18:08:08

标签: ios swift cocoa core-location

我在核心位置有问题,我已经按照设置进行了操作 https://stackoverflow.com/a/24696878/6140339这个答案,并将我的所有代码放在AppDelegate中,但我无法弄清楚如何调用它,所以我创建了另一个与didUpdateLocations相同的函数,并在我的findMyLocation按钮中调用它,它只返回零。

我已经尝试在Simulator中设置自定义位置,仍为零,我尝试使用调试器并设置位置,我甚至尝试在我的iphone上测试它,看看我是否可以获得一个位置,但仍然没有。

有没有办法从我的按钮调用didUpdateLocations? 或者我只是做了其他错误的事情,我错过了。

这是我的viewController中的代码:

import UIKit
import Social
import CoreLocation

class FirstViewController: UIViewController{

//let social = socialFunctions()
let locationManager = CLLocationManager()
let location = locationFunctions()
var locationFixAchieved = false
var currentLocation = CLLocation()

@IBOutlet weak var locationLabel: UILabel!

@IBAction func findMyLocation(sender: AnyObject) {
    updateLocation()
    print("Location: \(locationManager.location)")
}

@IBAction func postToFacebookButton(sender: UIButton) {
    postToFacebook()
}

@IBAction func postTweetButton(sender: UIButton) {
    postToTwitter()
}

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return .LightContent
}
override func viewDidLoad() {
    super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

//MARK: - SOCIAL FUNCTIONS
func postToFacebook(){
    if(SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)){
        let socialController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
        //creates post with pre-desired text
        socialController.setInitialText("")
        presentViewController(socialController, animated: true, completion: nil)
    }
}

func postToTwitter(){
    if(SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)){
        let socialController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
        //creates post with pre-desired text
        socialController.setInitialText("")
        presentViewController(socialController, animated: true, completion: nil)
    }
}

//MARK: - LOCATION FUNCTIONS
func updateLocation() {
    let locations = [CLLocation]()
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        let locationArray = locations as NSArray
        let locationObj = locationArray.lastObject as? CLLocation
        let coord = locationObj?.coordinate
        if coord?.latitude != nil {
            locationLabel.text = ("Location \r\n Latitude: \(coord?.latitude) \r\n Longitude: \(coord?.longitude)")
            print("Latitude: \(coord?.latitude)")
            print("Longitude: \(coord?.longitude)")
        } else {
            locationLabel.text = ("Could not find location")
            print("LAT & LONG are nil")
        }
    }
}

}

这是我添加到appDelegate

的代码
import UIKit
import CoreLocation
let fvc = FirstViewController()

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved: Bool = false
var locationStatus : NSString = "Not Started"

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
    initLocationManager();
    return true
}

func initLocationManager() {
    seenError = false
    locationFixAchieved = false
    locationManager = CLLocationManager()
    locationManager.delegate = self
    CLLocationManager.locationServicesEnabled()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest

    locationManager.requestAlwaysAuthorization()
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    locationManager.stopUpdatingLocation()
    if (error == true) {
        if (seenError == false) {
            seenError = true
            print(error)
        }
    }
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locations = [CLLocation]()
        if (locationFixAchieved == false) {
            locationFixAchieved = true
            let locationArray = locations as NSArray
            let locationObj = locationArray.lastObject as? CLLocation
            let coord = locationObj?.coordinate

            print("Latitude: \(coord?.latitude)")
            print("Longitude: \(coord?.longitude)")
            //fvc.locationLabel.text = ("Location \r\n Latitude: \(coord?.latitude) \r\n Longitude: \(coord?.longitude)")
    }
}

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 location Access"
        shouldIAllow = true
    }
    NSNotificationCenter.defaultCenter().postNotificationName("LabelHasBeenUpdated", object: nil)
    if (shouldIAllow == true) {
        NSLog("Location Allowed")
        //Start location services
        locationManager.startUpdatingLocation()
    } else {
        NSLog("Denied access: \(locationStatus)")
    }
}

1 个答案:

答案 0 :(得分:0)

关注dan的评论(谢谢)我所要做的就是删除第一行,它显示坐标,我还没弄明白如何调用我的函数来更改标签文本,但我会发布时间我明白了。编辑:在下面发布解决方案

我改变了

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locations = [CLLocation]()
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        let locationArray = locations as NSArray
        let locationObj = locationArray.lastObject as? CLLocation
        let coord = locationObj?.coordinate

        print("Latitude: \(coord?.latitude)")
        print("Longitude: \(coord?.longitude)")
        //fvc.locationLabel.text = ("Location \r\n Latitude: \(coord?.latitude) \r\n Longitude: \(coord?.longitude)")
}

}

删除let locations = [CLLocation]()

这是我按下按钮时的调用方式。

func updateLocation() {
    let manager = CLLocationManager()
    let locValue : CLLocationCoordinate2D = (manager.location?.coordinate)!;
    let long = locValue.longitude
    let lat = locValue.latitude
    print(long)
    print(lat)
    locationLabel.text = ("Location \r\nLatitude: \(lat) \r\nLongitude: \(long)")
    }