Ios 线程1:EXC_错误_指令
我正在制作这个应用程序,用户可以看到自己的位置和其他用户的位置。我最近刚听到一个错误,说 线程1:EXC_BAD_指令(代码=EXC_1386_INVOP,子代码=0x0) 在这一行:Ios 线程1:EXC_错误_指令,ios,swift,core-location,Ios,Swift,Core Location,我正在制作这个应用程序,用户可以看到自己的位置和其他用户的位置。我最近刚听到一个错误,说 线程1:EXC_BAD_指令(代码=EXC_1386_INVOP,子代码=0x0) 在这一行: var lat = locationManager.location?.coordinate.latitude 我还没把它修好 原因是什么?我如何修复它? 对于可能希望了解其余代码的任何人: import UIKit import Parse import CoreLocation import MapKit
var lat = locationManager.location?.coordinate.latitude
我还没把它修好
原因是什么?我如何修复它?
对于可能希望了解其余代码的任何人:
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")
}
}
问题是,您询问位置管理器的
位置
,而没有检查结果是否为nil
。嗯,是的(可能是因为还没有时间了解实际位置)。因此,当您尝试获取该位置的纬度和经度时,lat
和lon
,它们也是nil
。因此,当您强制展开它们时,您会崩溃,因为您无法展开nil
这就是所说的:
问题是您正在询问位置经理的位置 没有检查结果是否为零 以下是检查值是否为零的方法: 选项1:
guard let lat = locationManager.location?.coordinate.latitude else {
return
}
if let latCheck = locationManager.location?.coordinate.latitude {
// assign your lat value here
} else {
// handle the problem
}
选项2:
guard let lat = locationManager.location?.coordinate.latitude else {
return
}
if let latCheck = locationManager.location?.coordinate.latitude {
// assign your lat value here
} else {
// handle the problem
}
当你看到时,你需要改变你的心态代码>您可能应该使用上述两种方法之一展开可选值
根据评论更新:
guard let lat = locationManager.location?.coordinate.latitude else {
return
}
if let latCheck = locationManager.location?.coordinate.latitude {
// assign your lat value here
} else {
// handle the problem
}
您还可以尝试创建一个新的变量来使用,并查看其工作原理:
guard let location = locationManager.location else {
return
}
然后:
位置管理器应该是一个属性,而不是一个局部变量。现在,错误向下移动到let location=CLLocationCoordinate2D(纬度:lat!,经度:lon!)。该错误可能是由于使用“!”强制展开nil可选项引起的。您应该重写代码以避免使用“!”强制展开选项。切换到可选绑定以确定意外的nil值的位置。我不确定您是如何做到这一点的?请看我的更新。也许你能看出问题所在?谢谢你的时间和帮助IT仍然希望我用“!”@TomJames更新了另一种可能的解决方案,如果这不起作用,我回家后必须看一看