【问题标题】:swift 3 error using MapKit使用 MapKit 的 swift 3 错误
【发布时间】:2017-05-18 20:07:07
【问题描述】:

我正在制作地图

在info.plist中添加两个变量“Privacy - Location When Usage Description”, “Privacy - Location Always Usage Description”

错误: 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“无效区域”

我的代码:

import UIKit
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {


    @IBOutlet weak var map: MKMapView!

    var manager: CLLocationManager!


    override func viewDidLoad() {
        super.viewDidLoad()

        manager = CLLocationManager()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()

        let uilpgr = UILongPressGestureRecognizer(target: self, action:Selector(("action:")))
        uilpgr.minimumPressDuration = 2.0
        map.addGestureRecognizer(uilpgr)

    }

    func action(gestureRecognizer:UIGestureRecognizer){
        if gestureRecognizer.state == UIGestureRecognizerState.began{
        let touchPoint = gestureRecognizer.location(in: self.map)
            let newCoordinate = self.map.convert(touchPoint, toCoordinateFrom: self.map)
            let annotation = MKPointAnnotation()

            annotation.coordinate = newCoordinate
            annotation.title = "Meu lugar"
            self.map.addAnnotation(annotation)



        }
    }


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0]
        let latitude = userLocation.coordinate.latitude
        let longitude = userLocation.coordinate.longitude
        let coordinate = CLLocationCoordinate2DMake(longitude,latitude)
        let latDelta: CLLocationDegrees = 0.01
        let lonDelta: CLLocationDegrees = 0.01
        let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
        let region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span)
        self.map.setRegion(region, animated: false)

    }


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


}

【问题讨论】:

  • 错误信息不是很明显吗? region 似乎无效。
  • 也不需要所有的代码;您可以直接在地图视图上启用用户跟踪

标签: ios swift xcode


【解决方案1】:

我想你忘了导入 CoreLocation 框架。我认为您没有从委托方法中获取有效的位置对象。请导入 CoreLocation 框架并再次测试。

【讨论】:

  • 如果您已经导入了 MapKit,则无需导入 CoreLocation。 MapKit 已经导入 CoreLocation。
【解决方案2】:

locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 中的代码是多余的,因为您可以调用 self.map.setUserTrackingMode(.follow, animated: true)

如果用户要平移地图,用户跟踪将被禁用,因此您需要使用此委托mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) 来更新用户跟踪模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    相关资源
    最近更新 更多