Here's my code in 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)
}
}
Now, the error is described as thus:
fatal error: unexpectedly found nil while unwrapping an Optional value
Thread 1 is pointing towards this being the issue:
var latitude: Double = locationZoom.coordinate.latitude
However, when testing this on the simulator, I have also found the issue to occur with the longitude variable. Still, I do not understand why the values for both longitude and latitude are set to "nil." I have set up CLLocationManager correctly, made sure to modify info.plist as necessary to include NSLocationWhenInUseUsageDescription
and NSLocationAlwaysUsageDescription
, etc. What's going on, and how do I correct this issue?
This happens because when your view loads it has not received any location update. Implement DidUpdateLocations and access location info there. if you need reference you can look DidUpdateLocations