在Swift中找到用户位置

时间:2015-01-21 21:10:02

标签: ios swift core-location

我尝试使用CLLocationmanager将当前位置添加到地图中,但是当我尝试调用func mapView.StartUpdateLocation时,如何委托协议" didUpdateLocation"不被称为,任何知道如何解决这个问题?谢谢

import UIKit
import MapKit

class mapViewController: UIViewController, CLLocationManagerDelegate,   MKMapViewDelegate {

@IBOutlet var mapView: MKMapView!
var restaurant:Restaurant!
var locationManager = CLLocationManager()
var current: CLPlacemark!



override func viewDidLoad()
{
    super.viewDidLoad()


    mapView.delegate = self
    self.locationManager.requestAlwaysAuthorization()


    // convert address to coordinate
    let geoCoder = CLGeocoder()
    geoCoder.geocodeAddressString(restaurant.location, completionHandler: { (placemarks, error) -> Void in
        if error != nil
        {
            print(error)
            return
        }
        if placemarks.count > 0
        {
            let placemark = placemarks[0] as CLPlacemark

            // add annotation 

            let annotation = MKPointAnnotation()
            annotation.coordinate = placemark.location.coordinate
            annotation.title = self.restaurant.name
            annotation.subtitle = self.restaurant.type

            self.mapView.showAnnotations([annotation], animated: true)
            self.mapView.selectAnnotation(annotation, animated: true)
            self.mapView.showsUserLocation = true // add to show user location 

        }
    })
}

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

@IBAction func currentLocation(sender: AnyObject)
{
    if ( CLLocationManager.locationServicesEnabled())
    {
        println("Location service is on ")
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.stopUpdatingLocation()
    locationManager.startUpdatingLocation()
    }else
    {
        println("Location service is not on ")
    }



}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
        if error != nil
        {
            print("error")
        }
        if placemarks.count > 0
        {
            self.current = placemarks[0] as CLPlacemark
            let annotation = MKPointAnnotation()
            annotation.coordinate = self.current.location.coordinate

            self.mapView.showAnnotations([annotation], animated: true)
            self.mapView.selectAnnotation(annotation, animated: true)

        }
        else
        {
            print("I dont know what the fuck is the error")
        }
    })
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println(error.localizedDescription)
}

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!
{
    let indentifier = "My Pin"
    if annotation.isKindOfClass(MKUserLocation){ return nil }
     // Resuse Annotation if possiable 

    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(indentifier)
    if annotationView == nil
    {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: indentifier)
        annotationView.canShowCallout = true  // tell annotation can display
    }

    let iconImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 53, height: 53)) // create left icon image for annotation view 

    iconImageView.image = UIImage(named: restaurant.image)

    annotationView.leftCalloutAccessoryView = iconImageView

    return annotationView
}



/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

2 个答案:

答案 0 :(得分:1)

iOS7和iOS之间有变化8关于GPS定位。请阅读这篇文章。

http://matthewfecher.com/app-developement/getting-gps-location-using-core-location-in-ios-8-vs-ios-7/

也许您还没有将这些信息添加到.plist

<key>NSLocationAlwaysUsageDescription</key>
<string>Your message goes here</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your message goes here</string>

答案 1 :(得分:1)

请检查以下在info.plist中输入的密钥

NSLocationWhenInUseUsageDescription

NSLocationAlwaysUsageDescription

并设置

 var _locationManager = CLLocationManager()
    _locationManager.delegate = self
    _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    _locationManager.requestAlwaysAuthorization()

在viewDidLoad()