首页 > 解决方案 > 从地址获取坐标的完成处理程序

问题描述

我在完成处理程序周围有很多困难。而且我不知道如何使用它。

这是带有完成处理程序的函数,用于根据字符串地址获取地理坐标:

func getLocation(from address: String, completion: @escaping (_ location: CLLocation?)-> Void) {
        guard let address = address as? String else { return }
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(address) { (placemarks, error) in
            guard let placemarks = placemarks,
            let location = placemarks.first?.location else {
                completion(nil)
                return
            }
            completion(location)
        }
    }

我这样调用这个函数:

getLocation(from: address) { location in
            print("Location is", location.debugDescription)
            if case self.currentLocation = location {
                self.queryGenerator(searched: self.searchController.isActive, queryString: "")
            } else {
                self.showAlert(alertTitle: "No businsesses nearby", message: "Try going back and changing the address")
            }
        }

我不断得到零currentLocation。如果有人能帮我把这件事弄得一团糟,那就太好了。

在获得向我发送包含业务坐标和服务半径的自定义对象的位置后,我进行了网络调用。如果服务半径小于或等于业务坐标和 currentLocation 之间的距离,那么我将其添加到填充 UITableView 的数组中。这是我进行前面计算的函数:

func applicableRestaurants(allQueriedRestaurants: [Restaurant]) -> [Restaurant] {
        var filteredRestaurants = [Restaurant]()
        for thisRestaurant in allQueriedRestaurants {
            let restaurantCoordinate = CLLocation(latitude: thisRestaurant.geoPoint.latitude, longitude: thisRestaurant.geoPoint.longitude)
            if restaurantCoordinate.distance(from: self.currentLocation!) <= thisRestaurant.distance {
                filteredRestaurants.append(thisRestaurant)
            }
        }
        return filteredRestaurants
    }

标签: swiftcompletionhandler

解决方案


我的猜测(这只是一个猜测)是你在不理解它的含义的情况下使用了这个表达式:

if case self.currentLocation = location {
    self.queryGenerator...

你的意思可能是:

if let location = location {
    self.currentLocation = location
    self.queryGenerator...

我想你可能认为这些是等价的,但事实并非如此。


推荐阅读