import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapKit: MKMapView!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapKit.setRegion(region, animated: true)
self.mapKit.showsUserLocation = true
}
override func viewDidLoad() {
super.viewDidLoad()
let manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
}
}
这是我的源代码。我使用Xcode 9和swift 4.0
当我构建并运行时,调试区域打印此内容"无法在角落4"中插入法律归属,并使用GPS警报自动关闭。所以我不能接受使用GPS允许。
我也完成了像这样的info.plist设置。
隐私 - 位置始终和何时使用用法说明 隐私 - 位置始终使用说明 隐私 - 使用时的位置用法说明。
有什么问题?
答案 0 :(得分:0)
将CLLocationManager作为全局实例var -
@IBOutlet weak var mapKit: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span: MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
mapKit.setRegion(region, animated: true)
self.mapKit.showsUserLocation = true
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
}
这样可以防止警报自动解除。