【问题标题】:Downcast from 'CLLocation?' to 'CLLocation' only unwraps optionals; did you mean to use '!'?来自“CLLocation”的沮丧?到 'CLLocation' 只解开选项;你的意思是使用'!'?
【发布时间】: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


【解决方案1】:

您将Optional CLLocation 强制转换为CLLocation,这就是为什么 Swift 建议简单地强制解包:

let location = locations.last!

如果locations 为空,此版本(和您的版本)将崩溃。

因此我建议不要强行打开任何东西,而是使用guard

guard let location = locations.last else {
    return
}

【讨论】:

  • 谢谢,我现在没有收到任何错误,但是当它运行时,它只显示一个没有我位置的地图,知道为什么吗?
  • 那是另一个话题。遵循@Paulw11 的建议(启用用户跟踪模式)和/或为此发布另一个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 2011-01-20
相关资源
最近更新 更多