Search code examples
swiftcllocation

Post location to iCloud database using Swift


I am trying to post my location to an iCloud database. I keep getting an "Expected Declaration" error that I am trying to fix but am not sure what to do.

My code is as follows:

CLGeocoder *geocoder = [CLGeocoder new]

[geocoder geocodeAddressString:artwork[kArtworkAddressKey] completionHandler:^(NSArray *placemark, NSError *error){
    if (!error) {
        if (placemark.count > 0) {
            CLPlacemark *placement = placemark[0]
            artworkRecord[kArtworkLocationKey] = placement.location
        }   
    } else {
        // insert error handling here
    }
    // Save the record to the database  
}]

I am a novice, so please forgive if this is a simple question.

enter image description here


Solution

  • The problem is that you have put Objective-C into a Swift file. You can translate it like this...

    Objective-C

    CLGeocoder *geocoder = [CLGeocoder new]
    
    [geocoder geocodeAddressString:artwork[kArtworkAddressKey] completionHandler:^(NSArray *placemark, NSError *error){
        if (!error) {
            if (placemark.count > 0) {
                CLPlacemark *placement = placemark[0]
                artworkRecord[kArtworkLocationKey] = placement.location
            }   
        } else {
            // insert error handling here
        }
        // Save the record to the database  
    }]
    

    Swift...

    let geocode = CLGeocoder()
    
    geocoder.geocodeAddressString(artwork[kArtworkAddressKey]) {
        placemark, error in
        if error {
            // handle error
        } else {
            if let placement = placemark[0] {
                self.artworkRecord[kArtWorkLocationKey] = placement.location
            }
        }
    }
    

    Something like that anyway.