16

In Objective-C this code works fine to plot an address and it finds the longitude and latitude coordinates:

     NSString *address = @"1 Infinite Loop, CA, USA";
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:address 
             completionHandler:^(NSArray* placemarks, NSError* error){
                 // Check for returned placemarks
                 if (placemarks && placemarks.count > 0) {
                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                     // Create a MLPlacemark and add it to the map view
                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
                     [self.mapView addAnnotation:placemark];
                     [placemark release];
                 }
                 [geocoder release];
             }];

I have been searching for days on how to do this with Swift?! Could anyone point me in the right direction? Could you explain if a user needs an internet connection for this to work. Sorry if these questions sounds a bit basic, but I am quite new to this and learning every day.

I understand that I have to use this code, but cannot find a way to implement it

func geocodeAddressString(_ addressString: String!,
    completionHandler completionHandler: CLGeocodeCompletionHandler!)
agf119105
  • 1,770
  • 4
  • 15
  • 22

3 Answers3

38

XCode 9 & Swift 3:

import CoreLocation

let address = "1 Infinite Loop, CA, USA"
let geocoder = CLGeocoder()

geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
   if((error) != nil){
      print("Error", error)
   }
   if let placemark = placemarks?.first {
      let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
      }
    })
realtimez
  • 2,525
  • 2
  • 20
  • 24
27

Try something like

var address = "1 Infinite Loop, CA, USA"
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
    if let placemark = placemarks?[0] as? CLPlacemark {
        self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
    }
})
kviksilver
  • 3,824
  • 1
  • 26
  • 27
  • Thanks for the answer, but the placemarks: [AnyObject]! gives an error. @kviksilver – agf119105 Jul 13 '14 at 22:27
  • 1
    Replace that line with : geocoder.geocodeAddressString(address, {(placemarks: AnyObject[]!, error: NSError!) -> Void in if you are running beta < 3 – kviksilver Jul 14 '14 at 19:06
3
var address = "1 Infinite Loop, CA, USA"
var geocoder = CLGeocoder()    

geocoder.geocodeAddressString(address) {
    if let placemarks = $0 {
       println(placemarks)
    } else {
       println($1)
    }
}
MirekE
  • 11,515
  • 5
  • 35
  • 28