ios - 在 Swift 的 MKMapView 中显示当前位置和更新位置

标签 ios swift mkmapview cllocationmanager

我正在学习如何使用新的 Swift 语言(只有 Swift,没有 Objective-C)。为此,我想用 map (MKMapView) 做一个简单的 View 。我想查找并更新用户的位置(例如在 Apple map 应用中)。

我试过了,但什么也没发生:

import MapKit
import CoreLocation

class MapView : UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        if (CLLocationManager.locationServicesEnabled())
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    }
}

你能帮帮我吗?

最佳答案

您必须覆盖 CLLocationManager.didUpdateLocations(CLLocationManagerDelegate 的一部分)才能在位置管理器检索当前位置时得到通知:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last{
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.map.setRegion(region, animated: true)
    }
}

注意:如果您的目标是 iOS 8 或更高版本,您必须在 Info.plist 中包含 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 键以使位置服务正常工作。

关于ios - 在 Swift 的 MKMapView 中显示当前位置和更新位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449469/

相关文章:

arrays - String.init(stringInterpolation :) with an array of strings

swift - 如何检测用户滑动的方向?

iphone - MKMapView - 飞行模式开启时无法定位用户位置

ios - 自定义 UITableViewCell 的 UI 问题

ios - WSO2 EMM iOS 注册错误 : "The Registration Authority' s response is invalid"

iphone - 当 App 进入前台时调用 self.viewDidAppear

iphone - 将 MKMapView 与 kml 文件结合使用

ios - View 层次结构没有为约束准备?

ios - 自定义 UITableView 单元格图像转换不适用于可重用单元格

objective-c - iOS:在MKMapView中绘制具有固定半径的MKCircle?