Swift 4、Xcode 9:获取并显示用户的位置

jcdr04

我正在尝试获取并显示用户的位置,但模拟器只会加载我所在的国家/地区。我设置了所需的 info.plist 部分(隐私 - 使用时的位置和始终),链接 Main.storyoard 中的 mapView到委托(控制拖动到视图控制器图标),附加 IBOutlet(检查它以确保它正确连接)并在 viewController.swift 中编写以下代码:

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    var locationManager = CLLocationManager()

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        mapView.mapType = MKMapType.standard
        let location = locations[0]
        let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegion(center: myLocation, span: span)
        mapView.setRegion(region, animated: true)
        self.mapView.showsUserLocation = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.requestWhenInUseAuthorization()

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

我刚刚用 MapKit 弄湿了我的脚,这个问题已经让我退缩了很长一段时间。将不胜感激任何帮助。

乔根德拉·乔杜里

请使用 iPhone 设备获取当前位置。在模拟器中,您必须设置位置然后获取该位置。因此可以使用该设备轻松完成此操作。您的代码将适用于真实设备。

如果你想用模拟器测试它,请遵循https://medium.com/@abhimuralidharan/location-simulation-in-xcode-ff7db9042710

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

闭包元组不支持Xcode 9 Swift 4中的解构

Swift 4-Xcode 9 Beta 4-NSKernAttributeName与NSAttributedStringKey

Xcode 9卡在Swift 4迁移上

在Swift 4 Xcode 9 Beta 6中无法对UIButton进行编程,无法添加目标

更新到Xcode 9 / Swift 4后,AVCapture奇怪的编译错误

使用“新构建系统(预览版)”新功能时出现的问题Xcode 9 Swift 4

使用Swift 4 / Xcode 9从CLPLacemark获取完整的地址字符串

更新到Xcode 9和Swift 4

如何删除XCode9“有向Swift 4的转换可用”警告?

如何设置透明的导航栏?iOS 11 Swift 4 Xcode 9

MFMailComposeViewController,Swift 4,Xcode 9

Xcode 9中的Swift 4-如何在NSAttributedstring中使用boundingrect?

Swift4-Xcode 9 PCH错误

setValuesForKeys在Xcode 9中的Swift 4中不起作用

Xcode 9 / Swift 4 AVCaptureMetadataOutput setMetadataObjectTypes使用availableMetadataObjectTypes

蒸气不适用于xcode 9和swift 4

如何从数字键盘上调用textFieldShouldReturn Xcode 9 Swift 4

使用未声明的类型'Date'Xcode 9 Swift 4

Xcode 9 Swift 4 UITableView无法识别的选择器发送到实例

UIView动画Swift 4 Xcode9的问题

调整字体大小以适合标签高度-Swift 4,Xcode 9

PDFViewer SWIFT 4 Xcode 10.3

异步获取Swift Xcode

UnrecognizedSelector 如何在 Xcode9/Swift4 中成为可能?

使用 Swift 4 和 Xcode 9 获取 JSON 数据

Xcode 9 Swift 4 由于内存问题而终止(返回一个单元格)

Xcode 9 中的 Swift 4 - 读取核心数据中的数据失败

xcode9 swift4 致命错误:在展开可选值时意外发现 nil

位置标记不显示 Swift 4