Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protocol ReverseGeocodingHelper {
- typealias CountryComparisonCompletion = (Bool, [Error]?) -> ()
- func checkIf(location firstLocation:CLLocation, inTheSameCountryAs secondLocation:CLLocation, completion:@escaping CountryComparisonCompletion)
- }
- class CoreLocationReverseGeocodingHelper : ReverseGeocodingHelper{
- // typealias CountryComparisonCompletion = (Bool, [Error]?) -> ()
- func checkIf(location firstLocation:CLLocation, inTheSameCountryAs secondLocation:CLLocation, completion:@escaping CountryComparisonCompletion){
- //Declare variables that we would use after
- var firstLocationCountry : String?
- var secondLocationCountry : String?
- var errorInFirstLocationReverseGeocodingRequest : Error?
- var errorInSecondLocationReverseGeocodingRequest : Error?
- //Declare the dispatch group
- let dispatchGroup = DispatchGroup()
- //Declare nested function for each of the locations
- func reverseGeocodeFirstLocation(){
- dispatchGroup.enter()
- CLGeocoder().reverseGeocodeLocation(firstLocation) { (placemarks, error) in
- firstLocationCountry = placemarks?.first?.country
- errorInFirstLocationReverseGeocodingRequest = error
- dispatchGroup.leave()
- }
- }
- func reverseGeocodeSecondLocation(){
- dispatchGroup.enter()
- CLGeocoder().reverseGeocodeLocation(secondLocation) { (placemarks, error) in
- secondLocationCountry = placemarks?.first?.country
- errorInFirstLocationReverseGeocodingRequest = error
- dispatchGroup.leave()
- }
- }
- //Do the work in a dispatch group
- //Both functions enter the same dispatch group, so call both
- reverseGeocodeFirstLocation()
- reverseGeocodeSecondLocation()
- let queue:DispatchQueue = DispatchQueue.global(qos: .userInteractive)
- dispatchGroup.notify(queue: queue) {
- //Completion will be called only after both items reverse geocoding finished
- let errors : [Error] = [errorInFirstLocationReverseGeocodingRequest,errorInSecondLocationReverseGeocodingRequest].compactMap{$0} //Map only non nil to the array
- if errors.count > 0{
- completion(false,errors)
- }else{
- print("First locations is in:\(firstLocationCountry!)\n Second locations is in:\(secondLocationCountry!)")
- let bothLocationsInSameCountry : Bool = firstLocationCountry! == secondLocationCountry!
- completion(bothLocationsInSameCountry,nil)
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement