Location Operation(s)

Location Services wrapped up in Operations

Operations has support for location services on iOS.

User Location

UserLocationOperation can retrieve the location of the user's device. Internally it adds an AuthorizedFor condition using Capability.Location. See the section on Capabilities for more detailed information, but for now, it's enough to know that the operation will handle authorization for location services automatically.

The class can be used with a completion block as in the example below

let operation = UserLocationOperation { location in
    print("Location: \(location)")
}
queue.addOperation(operation)

Alternatively, UserLocationOperation sets the resultant CLLocation as a property: location.

let operation = UserLocationOperation()
operation.addObserver(FinishedObserver { op in
    if let op = op as? UserLocationOperation {
        print("Location: \(op.location)")    
    }
})
queue.addOperation(operation)

The above example is little redundant. A more likely usage of the location property would be when the operation is used inside of a GroupOperation subclass. See Groups for more guidance on creating groups.

Reverse Geocode

Core Location supports geocoding functionality. Reverse geocoding is where a known location is looked up to retrieve human readable location information such as an address. The actual result type for this information is a CLPlacemark.

In Operations, this can be used with a ReverseGeocodeOperation:

let operation = ReverseGeocodeOperation(location: aLocation) { placemark in
    print("Placemark: \(placemark)")
}
queue.addOperation(operation)

It also stores the received placemark in a property similar to UserLocationOperation.

Reverse Geocode User Location

Putting this all together, we have ReverseGeocodeUserLocation which first get the device's current location and then use that for a reverse geocode lookup. Therefore, if you functionality in your app where the user's can enter their current address, it might make sense to use this operation. The returned CLPlacemark can return a localized address information.

let operation = ReverseGeocodeUserLocation { location, placemark in
    print("Placemark: \(placemark)")
}
queue.addOperation(operation)

πŸ“˜

Accuracy

Both UserLocationOperation and ReverseGeocodeUserLocation accept a CLLocationAccuracy argument which has a sensible default value of three kilometers.

πŸ‘

Chain operations together with Result Injection

All location based operations conform to ResultOperationType which means their results can be injected as the requirement of other operations. See Injecting Results.