swift:使用当前位置的正确方法是什么

时间:2016-08-29 19:53:53

标签: ios swift uitableview uiviewcontroller mkmapview

我对swift和IOS开发很新。

我想问一下有经验的成员在一个viewcontroller中创建mapvie和tableview的正确方法是什么,并填充它们。

enter image description here

应用程序的逻辑如下:

  • 获取用户的当前位置
  • 读取带有POI坐标的plist文件
  • 为每个POI运行一个计算用户和点之间距离的函数
  • 使用plist文件中的数据和新计算的数据填充表。

mapview和tableview都在同一个viewcontroller中。

在viewDidLoad中的

我正在获取用户位置。

在viewwillappear中我正在运行函数来读取plist文件并计算POI和用户之间的距离。

一切正常但它不稳定...有时它可能会显示用户的位置,但表格将为空。所以我怀疑我正在做的一切正确。也可能将map和table放在一个类中是不正确的?

更新 这是代码:

import UIKit
import MapKit
import CoreLocation


class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate  {

    @IBOutlet weak var theMapView: MKMapView!
    @IBOutlet weak var tableView: UITableView!


    var locationManager: CLLocationManager!
    var branches = [Branch]()



    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()

        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.requestWhenInUseAuthorization()

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






            tableView.dataSource = self
            tableView.delegate = self


            locationManager.startUpdatingLocation()
            locationManager.startUpdatingHeading()


            //mapview setup to show user location
            theMapView.delegate = self
            theMapView.showsUserLocation = true
            theMapView.mapType = MKMapType(rawValue: 0)!
            theMapView.userTrackingMode = MKUserTrackingMode(rawValue: 2)! 
    }



    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        readFromPlist()

    }






    //MARK: UITableView methods
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return branches.count
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: MapCustomCell = tableView.dequeueReusableCellWithIdentifier("mapCell") as! MapCustomCell
        let brnch = branches[indexPath.row]
        cell.mapSetupCell(brnch.cityName, AddressLabel: brnch.address, DistanceLabel: brnch.distance)
        return cell
    }



    //MARK: FUNC TO CALCULATE DISTANCE
    func calculateDistance (lat1 lat1: Double, lon1: Double, lat2: Double, lon2: Double) -> String {

        return "100km"
    }



    func locationManager (manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let myCoordinates = locations.last
        let myLat = myCoordinates!.coordinate.latitude
        let myLong = myCoordinates!.coordinate.longitude

        let myCoordinates2D = CLLocationCoordinate2DMake(myLat, myLong)

        let myLatDelta = 0.10
        let myLongDelta = 0.10
        let mySpan = MKCoordinateSpanMake(myLatDelta, myLongDelta)

        let myRegion = MKCoordinateRegion(center: myCoordinates2D, span: mySpan)

        theMapView.setRegion(myRegion, animated: true)

        let myAnno = MKPointAnnotation()
        myAnno.coordinate = myCoordinates2D

        self.locationManager.stopUpdatingLocation()
    }


    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print("error:" + error.localizedDescription)
    }



    func readFromPlist() {

        //read plist file to extract banks coordinates
        let path = NSBundle.mainBundle().pathForResource("poi", ofType: "plist")
        let POIarrays = NSArray(contentsOfFile: path!)

        for arr in POIarrays! {

            var ctName : String!
            var brnchAddress : String!
            var wrkngHours : String!
            var lat : Double!
            var long : Double!

            ctName  = arr.objectForKey("cityName")! as! String
            brnchAddress  = arr.objectForKey("address")! as! String
            wrkngHours  = arr.objectForKey("workingHours")! as! String
            lat  = Double(arr.objectForKey("latitude")! as! String)
            long  = Double(arr.objectForKey("longitude")! as! String)


                let latitude: CLLocationDegrees = lat
                let longitude : CLLocationDegrees = long

                let bankLocation : CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)


                let annotation = MKPointAnnotation()
                annotation.coordinate = bankLocation
                annotation.title = bnkName
                annotation.subtitle = brnchAddress

                self.theMapView.addAnnotation(annotation)


                let myLatitude = self.locationManager.location?.coordinate.latitude
                let myLongitude = self.locationManager.location?.coordinate.longitude

                if myLatitude != nil {

                    let dist = calculateDistance(lat1: latitude, lon1: longitude, lat2: myLatitude!, lon2: myLongitude!)

                    let b = Branch(cityName: ctName!, address: brnchAddress!, distance: dist)

                    branches.append(b)

            }
        }

    }


}

有时我收到错误“错误:操作无法完成。(kCLErrorDomain error 0.)”并且我的地图上没有显示当前位置。

0 个答案:

没有答案