Showing posts with label Core Location. Show all posts
Showing posts with label Core Location. Show all posts

Monday, 10 November 2014

Swift + CLGeocoder to get address from current location

First of all add & Import CoreLocation framework in your class.

If you are working with iOS 8 you must include the NSLocationAlwaysUsageDescription key in info.plist file of your current project to get the location services to work.


import UIKit
import CoreLocation

class ViewController: UIViewControllerCLLocationManagerDelegate
{

    let locationManager = CLLocationManager()
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
      }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
       
    }

  

        //--- Find Address of Current Location ---//
    @IBAction func findMyLocation(sender: AnyObject)
    {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        
        
       let location = self.locationManager.location
        
        var latitude: Double = location.coordinate.latitude
        var longitude: Double = location.coordinate.longitude
        
        println("current latitude :: \(latitude)")
        println("current longitude :: \(longitude)")
        

    }






   You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
                 //--- CLGeocode to get address of current location ---//
        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
            
            if (error != nil)
            {
                println("Reverse geocoder failed with error" + error.localizedDescription)
                return
            }
            
            if placemarks.count > 0
            {
                let pm = placemarks[0] as CLPlacemark
                self.displayLocationInfo(pm)
            }
            else
            {
                println("Problem with the data received from geocoder")
            }
        })        

    }


    func displayLocationInfo(placemark: CLPlacemark?)
    {
        if let containsPlacemark = placemark
        {
            //stop updating location to save battery life
            locationManager.stopUpdatingLocation()
            
            let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
            let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
            let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
            let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
            
            println(locality)
            println(postalCode)
            println(administrativeArea)
            println(country)
        }
        
    }
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
    {
        println("Error while updating location " + error.localizedDescription)
    }




}

Swift + Show Current Location and Update Location in a MKMapView

First of all add & Import CoreLocation and MapKit framework in your class.

If you are working with iOS 8 you must include the NSLocationAlwaysUsageDescription key in info.plist file of your current project to get the location services to work.


import UIKit
import CoreLocation

import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate
{

    @IBOutlet weak var map: MKMapView!
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
       self.map.mapType = MKMapType.Standard
       self.map.showsUserLocation = true
        
       self.map.removeAnnotations(self.map.annotations)





        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        
        
        let location = self.locationManager.location
        
        var latitude: Double = location.coordinate.latitude
        var longitude: Double = location.coordinate.longitude
        
        println("current latitude :: \(latitude)")
        println("current longitude :: \(longitude)")






    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
       
    }


   You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
        //-
        
        let location = locations.last as CLLocation
        
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        
        
        self.map.setRegion(region, animated: true)
        
    
        // Add an annotation on Map View
        var point: MKPointAnnotation! = MKPointAnnotation()
        
        point.coordinate = location.coordinate
        point.title = "Current Location"
        point.subtitle = "sub title"
        
        self.map.addAnnotation(point)
        
        //stop updating location to save battery life
        locationManager.stopUpdatingLocation()

    }


//--- Uncomment to add custom annotation view ---//

    /*
    //--- use this code to add custom image (Annotation) for pin point ---//
    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! 
{
        if !(annotation is MKPointAnnotation)
        {
            return nil
        }
        
        let reuseId = "test"
        
        var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
        
        if anView == nil
        {
            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView.image = UIImage(named:"1.png")
            anView.canShowCallout = true
        }
        else
        {
            anView.annotation = annotation
        }
        
        return anView
    }
    */



}