目前,我正在尝试使用MKLocalSearch来显示用户的相关信息,但问题是总是会出现致命错误:在展开可选值时意外发现nil。我已尝试确保没有可选值,但仍收到错误
import UIKit
import MapKit
import CoreLocation
class MapKitViewController: UIViewController {
@IBOutlet weak var MapAround: MKMapView!
let locationManger:CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
var viewRegion = MKCoordinateRegion(center: MapAround.userLocation.location.coordinate, span: span)
var request = MKLocalSearchRequest()
request.naturalLanguageQuery = "restaurants"
request.region = MKCoordinateRegion(center: MapAround.userLocation.location.coordinate, span: span)
let search = MKLocalSearch(request: request)
search.startWithCompletionHandler {
(response:MKLocalSearchResponse!, error:NSError!) -> Void in
if (error == nil) {
println("searched")
for item in response.mapItems as [MKMapItem]{
println("Item name = \(item.name)")
}
} else {
println(error)
}
}
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
var viewRegion = MKCoordinateRegion(center: MapAround.userLocation.location.coordinate, span: span)
MapAround.setRegion(viewRegion, animated: true)
}
}有人知道问题出在哪里吗?
谢谢!!
发布于 2014-12-15 09:02:44
您有两个隐式展开的选项,即MKMapView和userLocation。您可能需要检查这两个文件是否为nil。地图视图不应该是nil,除非插座没有正确连接,或者视图控制器没有正确实例化。如果位置服务还没有确定用户的位置,则可以想象userLocation是nil。
一般来说,当您第一次启动位置服务时(通过地图的"show user location“功能,或者手动启动位置服务),在实际确定用户位置之前需要花费一些时间。因此,在尝试直接在viewDidLoad中使用该位置时,应谨慎行事。
相反,您应该实现MKMapViewDelegate方法didUpdateUserLocation (并且不要忘记设置映射视图的delegate )。该函数将在用户位置更新时调用,在此之前,您应该避免尝试使用该位置。
或者,您可以启动CLLocationManager的位置服务并等待didUpdateLocations ( CLLocationManagerDelegate方法之一)。但概念是相同的:认识到确定用户的位置是异步发生的,所以等待操作系统告诉你它确定了用户的位置(对于您的应用程序来说,这是一个足够准确的位置)。
话虽如此,我实际上更倾向于将这个搜索作为地图视图的regionDidChangeAnimated的一部分来实现。您可能希望搜索可见地图,而不是用户的当前位置。如果你碰巧使用的是.Follow的userTrackingMode,它也是等同的,但如果你曾经考虑让用户移动地图(例如,让用户搜索他们要去的地方,而不是他们当前在哪里),regionDidChangeAnimated可能更有意义。
https://stackoverflow.com/questions/27475809
复制相似问题