Location Demo in iOS 8 With Swift

What we will be doing is a simple app the tells your location base on the longitude and latitude.


   For making things simpler, I already set-up the UI in this link. Once you have downloaded the files go to storyboard and change the size class from wAny|hANy to wCompact|hRegular. Here is what the story board should look like:





First, add "CoreLocation" to the framework.

Once added, inside the "ViewController.swift" import CoreLocation and add CLLocationManagerDelegate.

Then declare the following variables:

    var locationManager : CLLocationManager = CLLocationManager()
    
    var geocoder : CLGeocoder = CLGeocoder()
    var placemark : CLPlacemark = CLPlacemark()

Then insert the following lines of code:

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        println("didFailWithError %@", error)
        var errorAlert : UIAlertView = UIAlertView(title: "Error", message: "Failed to get your location", delegate: nil, cancelButtonTitle: "OK")
        
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        //println("didUpdateToLocation %@",locations)
        
        var currentLocation : CLLocation = locations[0] as CLLocation
        
        if currentLocation != nil{
            var stringLongitude : NSString = NSString(format: "%0.8f", currentLocation.coordinate.longitude)
            var stringLatitude : NSString = NSString(format: "%0.8f", currentLocation.coordinate.latitude)
            lbl_longitude.text = stringLongitude
            lbl_latitude.text = stringLatitude
        }
        
        locationManager.stopUpdatingLocation()
    
        
        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
            
            if error {
                //println(“Reverse geocoder failed with error” + error.localizedDescription)
                println("Reverse geocode failed with error")
                return
            }
            
            if placemarks.count > 0 {
                let pm = placemarks[0] as CLPlacemark
                self.displayLocationInfo(pm)
            } else {
               // println(“Problem with the data received from geocoder”)
                println("Problem with the date recieved from geocoder")
            }

        })
        
    
    }
    
    func displayLocationInfo(placemark: CLPlacemark) {
        if placemark != nil {
            
            var tempString : String = ""
            
            if(placemark.locality != nil){
                tempString = tempString +  placemark.locality + "\n"
            }
            if(placemark.postalCode != nil){
              tempString = tempString +  placemark.postalCode + "\n"
            }
            if(placemark.administrativeArea != nil){
                tempString = tempString +  placemark.administrativeArea + "\n"
            }
            if(placemark.country != nil){
               tempString = tempString +  placemark.country + "\n"
            }
            
            lbl_address.text = tempString
            
        }
    }

After inserting the lines of code, insert this lines of code inside the button method:


        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

Last, inside the Info.plist, add NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription with both boolean value set to YES.

And that's it. Build and Run the project and you should now be able see your address.
Location Demo in iOS 8 With Swift Location Demo in iOS 8 With Swift Reviewed by Edmond Legaspi on Thursday, August 21, 2014 Rating: 5

No comments:

Powered by Blogger.