I am making this app where users can see their own location and other users location. I recently just got an error saying
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP,subcode=0x0)
at this line:
var lat = locationManager.location?.coordinate.latitude
I have not managed to fix it.
What is causing it and how can I fix it?
For any who might would like the rest of the code:
import UIKit
import Parse
import CoreLocation
import MapKit
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var myLocation: [CLLocation] = []
@IBOutlet weak var MapView: MKMapView!
@IBOutlet var UsernameTextField: UITextField!
@IBOutlet var PasswordTF: UITextField!
@IBOutlet var EmailTF: UITextField!
var locationManager: CLLocationManager!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let locationManager = CLLocationManager()
let lat = locationManager.location!.coordinate.latitude
let lon = locationManager.location!.coordinate.longitude
let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegionMake(location, span)
MapView!.setRegion(region, animated: true)
let anotation = MKPointAnnotation()
anotation.coordinate = location
anotation.title = "My tittle"
anotation.subtitle = "My Subtitle"
MapView!.addAnnotation(anotation)
print("Welcome in MapViewController")
}
}
The problem is that you are asking for the location manager's location
without checking to see whether the result is nil
. Well, it is (probably because there has not been time to get the actual location yet). Therefore, when you try to get that location's latitude and longitude, lat
and lon
, they are nil
as well. Therefore when you force-unwrap them, you crash, because you cannot unwrap nil
.
This is what @matt is talking about:
The problem is that you are asking for the location manager's location without checking to see whether the result is nil
Here's how you check to see if your value is nil:
option 1:
guard let lat = locationManager.location?.coordinate.latitude else {
return
}
option 2:
if let latCheck = locationManager.location?.coordinate.latitude {
// assign your lat value here
} else {
// handle the problem
}
You need to change your mindset, when you see an !
you should probably be unwrapping your optional value in one of the above two ways.
update based on comments:
You can also try creating a new variable to work with and see how it works:
guard let location = locationManager.location else {
return
}
then:
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.