gpt4 book ai didi

swift - 不使用 CLLocationManager 显示当前位置

转载 作者:行者123 更新时间:2023-11-28 07:06:20 26 4
gpt4 key购买 nike

我是 iOS 新手,我有一个关于查找当前用户位置的问题。我正在阅读 Apple 文档:

Displaying the User’s Current Location on the Map Map Kit includes built-in support for displaying the user’s current location on the map. To show this location, set the showsUserLocation property of your map view object to YES. Doing so causes the map view to use Core Location to find the user’s location and add an annotation of type MKUserLocation to the map.

The addition of the MKUserLocation annotation object to the map is reported by the delegate in the same way that custom annotations are. If you want to associate a custom annotation view with the user’s location, you should return that view from your delegate object’s mapView:viewForAnnotation: method. If you want to use the default annotation view, return nil from that method. To learn more about adding annotations to a map, see Annotating Maps.

而且听起来很棒。但是……

import UIKit
import MapKit

class ViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
super.viewDidLoad()

//set initial location in Honolulu
//let initialLocation = CLLocation(latitude: 21.282778, longitude: -157.829444)

mapView.showsUserLocation = true
let initialLocation = mapView.userLocation.location

centerMapOnLocation(initialLocation)

// let artwork = Artwork(title: "King David Kalakaua", locationName: "Waikiki Gateway Park", discipline: "Sculpture", coordinate: CLLocationCoordinate2D(latitude: 21.283921, longitude: -157.831661))

// mapView.addAnnotation(artwork)
//
// mapView.delegate = self
}

let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation){
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion,animated:true)
}
}

而且我遇到了一个 fatal error :在展开可选值时意外发现 nil。我不明白为什么。如果我手动设置位置 - 当然没问题。但是在文档中写到它将在 map 上添加注释。没有添加注释,它崩溃了。不使用 CLLocationManager 是否可以获取用户坐标?

最佳答案

您是否已请求用户允许您的应用使用定位服务? Apple 的文档可以帮助您解决这个问题。查看下面的示例代码以帮助您入门:

private func beginLocationUpdates() {
// Request location access permission
_locationManager!.requestWhenInUseAuthorization()

// Start observing location
_locationManager!.startUpdatingLocation()
}

关于swift - 不使用 CLLocationManager 显示当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30465740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com