Swift: как правильно работать с текущим местоположениемIOS

Программируем под IOS
Ответить
Anonymous
 Swift: как правильно работать с текущим местоположением

Сообщение Anonymous »

Я новичок в разработке Swift и IOS.
Я хотел бы спросить опытных участников, как правильно создать представление карты и таблицы в одном контроллере представления и заполнить их. p>
Изображение

логика применения следующая:
  • получить текущее местоположение пользователя
  • прочитать файл plist с координатами POI
  • для каждого POI запустить функция, которая вычисляет расстояние между пользователем и точкой.
  • заполняет таблицу данными из файла plist, а также вновь рассчитанными данными.
И MapView, и TableView находятся в одном и том же контроллере представления.
in viewDidLoad Я получаю местоположение пользователей.
В viewwillappear я запускаю функции для чтения файла plist и расчета расстояний между POI и пользователем.
Все работает но он нестабилен... иногда он может показывать местоположение пользователя, но таблица будет пустой. Вот и сомневаюсь, что все делаю правильно. Также, наверное, неправильно помещать карту и таблицу в один класс?
Обновить

Вот код:

Код: Выделить всё

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 0. )"

и текущее местоположение не отображается на моей карте.

Подробнее здесь: https://stackoverflow.com/questions/392 ... t-location
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»