我使用Swift创建了这个ViewController。它的工作是跟踪地理位置,在地图上绘制一条线,并将其保存到核心数据对象中。我只想要一些建议,改善地理定位跟踪使用核心位置和存储信息使用核心数据。
import CoreLocation
import MapKit
import UIKit
import CoreData
class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var lblCurrentLocation: UILabel!
var locationManager = CLLocationManager()
var userLocations:[CLLocation] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//setup coreLocation manager
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
//setup map
mapView.delegate = self;
mapView.mapType = MKMapType.Standard
mapView.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lblCurrentLocation.text = "\(locations[0])"
userLocations.append(locations[0] as CLLocation)
let spanX = 0.007
let spanY = 0.007
let newRegin = MKCoordinateRegion(center: mapView.userLocation.coordinate, span:MKCoordinateSpanMake(spanX, spanY))
mapView.setRegion(newRegin, animated: true)
if (userLocations.count > 1){
let sourceIndex = userLocations.count - 1
let destinationIndex = userLocations.count - 2
let c1 = userLocations[sourceIndex].coordinate
let c2 = userLocations[destinationIndex].coordinate
var a=[c1, c2]
let polyline = MKPolyline(coordinates: &a, count:a.count)
mapView.addOverlay(polyline)
}
print("\(userLocations)")
}
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 4
return polylineRenderer
}
return MKPolylineRenderer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func getMyLocation(sender: AnyObject) {
let locValue:CLLocationCoordinate2D = locationManager.location!.coordinate
self.lblCurrentLocation.text = "locations = \(locValue.latitude) \(locValue.longitude)"
}
@IBAction func startTracking(sender: AnyObject) {
locationManager.startUpdatingLocation()
}
@IBAction func endTracking(sender: AnyObject) {
locationManager.stopUpdatingLocation()
saveUserLocation()
}
func saveUserLocation(){
for location in userLocations {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("Location",
inManagedObjectContext: managedContext)
let locationEn = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext:managedContext)
locationEn.setValue(location.timestamp,forKey:"timestamp")
locationEn.setValue(location.coordinate.latitude,forKey:"latitude")
locationEn.setValue(location.coordinate.longitude,forKey:"longitude")
do{
try managedContext.save()
}catch let error as NSError{
print("error saving core data: \(error)")
}
}
}
}发布于 2016-03-30 00:03:50
你已经知道你的viewDidLoad方法应该是什么样子了.你只是不知道它应该是什么样子。它应该是这样的:
override func viewDidLoad() {
super.viewDidLoad()
setUpCoreLocationManager()
setUpMap()
}如果你有一个代码块,上面有一个注释告诉你它是做什么的,那么你有一个代码块和一个方法名.你只需要把它重构成那样。
var locationManager = CLLocationManager()这可能是一个let。我看不出我们为什么要改变这个。
userLocations.append(locations[0] as CLLocation)这种转换是不必要的,我对Xcode没有给出警告(也许是这样)感到惊讶。但我也很担心locations[0]。文档可能保证locations数组中始终至少有一个对象,但要知道这一点,我必须查看苹果的文档。此外,规则可能会改变,现在突然之间,你就会崩溃。
我更希望看到这个:
if location = locations.first {
userLocations.append(location)
}一般来说,这种方法func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])做的太多了。我更希望看到它看起来更像这样:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
userLocations.append(location)
updateMap()
}
}其中,updateMap()是一种方法,它在该方法的其余部分中绘制您要绘制的线。
在这个方法中,func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer,我可以用一个guard来逆转嵌套:
guard overlay is MKPolyline else {
return MKPolylineRenderer()
}
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 4
return polylineRenderer不过,我也想说明一下,我们可以为MKPolylineRenderer编写一个方便的初始化器,所以最后四行就变成了:
return MKPolylineRenderer(overlay: overlay, color: UIColor.blueColor(), lineWidth: 4)override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}如果您只是为了调用Super而重写一个方法,则根本不需要在这个类中实现该方法。只需从源代码中完全省略此方法即可。
//setup coreLocation manager
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters您应该与您对self的使用保持一致,Swift社区的一般感觉是,您应该在没有必要时忽略它。
此外,在这里要求始终和何时使用授权都是没有意义的。你只能要求其中一个。你只能问一次。
不过,我强烈建议您在这里采取完全不同的方法。首先,您应该向用户解释您即将请求许可,并解释原因。在这里,让他们选择完全退出。一旦你向操作系统请求许可,你就再也不能问了,所以如果用户拒绝,你就不能让操作系统再次提示他们。
您应该有一个弹出,其中包含类似以下内容的文本:
我们需要收集您的位置数据,以便<#Foo栏的事情,您的应用程序Does#>。如何共享您的位置数据?
如果他们选择“总是”,那么您就请求“始终授权”。
如果他们只选择什么时候应用程序是开放的,那么你在使用授权时请求。
如果他们选择永不,你两者都不做,也许你需要解雇这个视图控制器.但那样的话,你就不会向操作系统索要任何东西。你等到下一次他们来到这个屏幕,然后再问他们一次。
这种向用户请求权限的方法使用户在通过操作系统进行请求时实际给予您权限的可能性要高得多,并且允许您有机会再次询问他们是否允许第一次访问。
最后,您在这个文件中有一些选项、样式和缩进的问题。您可以安装并运行金丝来自动处理其中的大部分问题,并在Xcode中为其余部分生成警告,这样您就可以很容易地看到需要纠正的问题所在。
https://codereview.stackexchange.com/questions/124110
复制相似问题