【发布时间】:2017-09-16 19:42:27
【问题描述】:
我正在尝试在地图视图上显示用户当前位置,但在位置管理器功能的第一行出现错误
这是我的代码
import UIKit
import MapKit
class FirstViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapkitView: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad()
{
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last as! CLLocation
let center = CLLocationCoordinate2DMake(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapkitView.setRegion(region, animated: true)
}
}
我得到的错误是“来自 'CLLocation 的向下转换?' to 'CLLocation' 只解开可选项;你的意思是使用 '!' 吗?
在线让 location = locations.last as! CL位置
【问题讨论】:
-
你不需要
as! CLLocation,因为数组包含CLLocation,你可以说locations.last!,但请不要。使用有条件的展开if let location = locations.last {。但是,如果您阅读MKMapView的文档,您会发现如果您启用用户跟踪模式,它可以为您完成所有这些工作。 -
谢谢,我现在没有收到任何错误,但是当它运行时,它只显示一个没有我位置的地图,知道为什么吗?
-
是否提示您允许位置访问?你是在模拟器还是真机上测试?如果是模拟器,您是否从菜单中模拟了一个位置?如果是真机,它有定位吗?
-
啊,我必须在 Xcode 中模拟一个位置,谢谢 :D
标签: ios swift cllocation