ios - 位置坐标在 swift 中返回 nil

标签 ios iphone xcode swift ios8

坐标返回 nil,我在 plist 文件中输入了 requestAlwaysAuthorization 和 requestWhenInUseAuthorization,但仍然没有任何反应。 这是我的代码。

这段代码是怎么回事?我找不到错误在哪里。它只是为坐标返回 nil

import UIKit
import CoreLocation

class ViewController: UIViewController,CLLocationManagerDelegate {
//Location
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
var locationManager: CLLocationManager!
var userLocation : String!
var userLatitude : Double!
var userLongitude : Double!

//Current weather Outlets "Display Objects"
@IBOutlet weak var userLocationLabel: UILabel!
@IBOutlet weak var visibilityLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var currentTimeLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var precipitationLabel: UILabel!
@IBOutlet weak var summaryLabel: UILabel!
@IBOutlet weak var windSpeedLabel: UILabel!
@IBOutlet weak var refreshButton: UIButton!
@IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!


//API KEY
private let apiKey = "09ca8e3e75fafbadaf4b8594dabe860e"

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from         a nib.
    refreshActivityIndicator.hidden = true
    getCurrentWeatherData()
}


//Location Code

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

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

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in

        let pm = placemarks[0] as! CLPlacemark
        self.displayLocationInfo(pm)
    })

    if (locationFixAchieved == false) {
        locationFixAchieved = true
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as! CLLocation
        var coord = locationObj.coordinate
        self.userLatitude = coord.latitude
        self.userLongitude = coord.longitude

        getCurrentWeatherData()


    }
}


func displayLocationInfo(placemark: CLPlacemark?) {
    if let containsPlacemark = placemark {
        //stop updating location to save battery life
        locationManager.stopUpdatingLocation()
        let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
        let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
        let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
        let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
        //println(locality)
        //println(postalCode)
        //println(administrativeArea)
        //println(country)

        self.userLocationLabel.text = "\(locality), \(administrativeArea)"
    }
}


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)")
        }
}


func getCurrentWeatherData() -> Void {
    userLocation = "\(userLatitude),\(userLongitude)"

    // DC cord. = "44.029002,-92.855343"
    //URL
    let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
    let forecastURL = NSURL(string:"\(userLocation)", relativeToURL: baseURL)


    // creates data object; to get and save data from online
    let sharedSession = NSURLSession.sharedSession()
    let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location:NSURL!, response:NSURLResponse!, error: NSError!) -> Void in

        // if everything goes alright (no errors then run code)
        if (error == nil) {

            //turn JSON dictionary to NSDictionary so it's easier to work with
            let dataObject = NSData(contentsOfURL: location)
            let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary

            //bring weather dictionary from the CurrentWeather file
            let currentWeather = Current(weatherDictionary: weatherDictionary)
            println(weatherDictionary)

            //update view with current weather information
            dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                self.temperatureLabel.text = "\(currentWeather.temperature)"
                self.iconView.image = currentWeather.icon!
                self.currentTimeLabel.text = "\(currentWeather.currentTime!)"
                self.humidityLabel.text = "\(currentWeather.humidity * 100)%"
                self.precipitationLabel.text = "\(currentWeather.precipProbability * 100)%"
                self.summaryLabel.text = "\(currentWeather.summary)"
                self.windSpeedLabel.text = "\(currentWeather.windSpeed) MPH"
                self.visibilityLabel.text = "\(currentWeather.visibility) Mi"

                //stop refresh animation
                self.refreshActivityIndicator.stopAnimating()
                self.refreshActivityIndicator.hidden = true
                self.refreshButton.hidden = false
            })
 }

 else {

        let networkIssueController = UIAlertController(title: "Error", message: "Network Connectivity Error! Can't load data", preferredStyle: .Alert)
     println(error)
            //information for ok button in alertView
        let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
        networkIssueController.addAction(okButton)

            //information for cancel button in alertView
        let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
        networkIssueController.addAction(cancelButton)

        //if an error occurs show alert
        self.presentViewController(networkIssueController, animated: true, completion: nil)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
        //Stop refresh animation
        self.refreshActivityIndicator.stopAnimating()
        self.refreshActivityIndicator.hidden = true
        self.refreshButton.hidden = false

        })

        }
})

    downloadTask.resume()
}
//refresh method
@IBAction func refresh() {
    getCurrentWeatherData()
    refreshButton.hidden = true
    refreshActivityIndicator.hidden = false
    refreshActivityIndicator.startAnimating()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

最佳答案

也许您已经在未显示的代码中处理了所有这些情况,但这里列出了我认为您的代码中缺少的内容:

  • 我不认为你调用initLocationManager在你的代码中。
  • getCurrentWeatherData()在你的viewDidLoad()行不通,你需要从 locationManager(didUpdateLocations) 调用它.
  • 正在添加 requestAlwaysAuthorizationrequestWhenInUseAuthorization仅针对应用程序选项是不够的。您还需要提供 NSLocationAlwaysUsageDescription并附上说明您为何需要访问权限的文字。
  • 您需要检查授权状态。如果不确定,则需要请求访问并实现回调以等待用户响应。如果您以未确定的任何其他状态调用 requestAuthorization,我相信该函数不会执行任何操作,也不会提供任何反馈。
  • 为了进一步排除故障,我建议您 (1) 获取授权状态,以及 (2) 在 locationManager(didUpdateLocations) 上放置打印语句或断点看看它是否被调用。

关于ios - 位置坐标在 swift 中返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724900/

相关文章:

ios - 未调用函数 didSelectPost() - iOS 共享扩展

objective-c - For 循环会按照此模式在索引 : 0, 1 然后 1,2 然后 2,3 然后 3,4 处给我对象,直到数组计数?

iphone - 为 UIButton 设置 titleLabel

iphone - 我想使用 NSString filePaths 还是 NSURLs ?

iPhone无需登录即可发布到Google fusion表

iphone - “由于未捕获的异常而终止应用程序”..它找不到不再存在的主窗口

ios - UITableViewCell。如何在着陆期间突出显示单元格?

ios - 通过 iOS App 销售 iBooks

C语言重载

ios - 如何在不使用 Any BaseUIViewController 的情况下禁用所有 UIViewController 的暗模式?