这是我在ViewController.swift中的代码:
import UIKit
import Alamofire
import SwiftyJSON
import MapKit
import CoreLocation
import TwitterKit
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var myMap: MKMapView!
@IBOutlet weak var counterLabel: UILabel!
var manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//calling CLLocation
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
//map region
let locationZoom = self.manager.location
var latitude: Double = locationZoom.coordinate.latitude
var longitude: Double = locationZoom.coordinate.longitude
var centerLatitude: CLLocationDegrees = locationZoom.coordinate.latitude
var centerLongitude: CLLocationDegrees = locationZoom.coordinate.longitude
var latDelta: CLLocationDegrees = 0.03
var longDelta: CLLocationDegrees = 0.03
var span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(centerLatitude, centerLongitude)
var region: MKCoordinateRegion = MKCoordinateRegionMake(location, span) // this creates a map region with the center
myMap.setRegion(region, animated: true)
}
@IBAction func zoom(sender: AnyObject) {
let locationZoom = self.manager.location
var latitude: Double = locationZoom.coordinate.latitude
var longitude: Double = locationZoom.coordinate.longitude
var centerLatitude:CLLocationDegrees = locationZoom.coordinate.latitude
var centerLongitude: CLLocationDegrees = locationZoom.coordinate.longitude
var latDelta:CLLocationDegrees = 0.03
var longDelta:CLLocationDegrees = 0.03
var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(centerLatitude, centerLongitude)
var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) // this creates a map region with the center
myMap.setRegion(region, animated: true)
}
}
现在,错误描述如下:
致命错误:在解包可选值时意外发现nil
线程1指向这个问题:
var latitude: Double = locationZoom.coordinate.latitude
但是,在模拟器上测试时,我也发现了经度变量的问题。不过,我不明白为什么经度和纬度的值都设置为“零”。我已正确设置CLLocationManager,请确保根据需要修改info.plist以包含NSLocationWhenInUseUsageDescription
和NSLocationAlwaysUsageDescription
等。发生了什么,以及如何更正此问题?
答案 0 :(得分:3)
这是因为当你的视图加载时它没有收到任何位置更新。在那里实施DidUpdateLocations并访问位置信息。如果您需要参考,可以查看DidUpdateLocations
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let locationZoom = locations.last as! CLLocation
let latitude: Double = locationZoom.coordinate.latitude
let longitude: Double = locationZoom.coordinate.longitude
println(latitude)
println(longitude)
}