Ios swift:使用当前位置的正确方法是什么
我对swift和IOS开发非常陌生 我想问有经验的成员,在一个viewcontroller中创建mapvie和tableview并填充它们的正确方法是什么 应用逻辑如下:Ios swift:使用当前位置的正确方法是什么,ios,swift,uitableview,uiviewcontroller,mkmapview,Ios,Swift,Uitableview,Uiviewcontroller,Mkmapview,我对swift和IOS开发非常陌生 我想问有经验的成员,在一个viewcontroller中创建mapvie和tableview并填充它们的正确方法是什么 应用逻辑如下: 获取用户的当前位置 读取具有POI坐标的plist文件 对于每个POI运行,一个函数将计算用户和点之间的距离 使用plist文件中的数据和新计算的数据填充表 mapview和tableview都位于同一个viewcontroller中 在viewDidLoad中,我获取用户的位置 在VIEWWILLISE中,我正在运行函
- 获取用户的当前位置
- 读取具有POI坐标的plist文件
- 对于每个POI运行,一个函数将计算用户和点之间的距离
- 使用plist文件中的数据和新计算的数据填充表李>
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)”,并且当前位置未显示在我的地图上。请显示您的代码,以便我们更好地了解可能出现的错误,我们将乐于提供帮助!获取用户位置不是一次性的事情。用户的位置会随着时间的推移而改变,在最初的30秒左右会变得更加准确。正如杰克所说,展示你的代码。你是怎么知道位置的?在iOS 9上,您可以使用
requestLocation
,但在早期版本上,您需要获得多个位置更新,并检查水平精度
请参见。@Paulw11这就是重点。我认为有时需要一些时间来查找位置,并且在不填充表的数组的情况下向前运行。有时我还收到一个错误“错误:操作无法完成。(kCLErrorDomain错误0。)”您应该在使用时请求,或者始终请求授权。在didUpdateLocations方法中,不应调用stopUpdateLocation
。现实世界是混乱的。位置不精确,尤其是第一次修复。正如我所说,ios9提供了一个很好的“requestLocation”方法,可以为您提供一个单一、准确的位置(如果可以,位置并不总是可用的,例如室内),但ios8需要您自己完成工作;当您获得新位置时,需要重新计算表距离计算;在单元格中计算距离,然后在位置更新时重新加载表格