【问题标题】:Completion handler for getting coordinates from address从地址获取坐标的完成处理程序
【发布时间】:2020-04-16 16:29:02
【问题描述】:

我很难理解完成处理程序。而且我不知道如何使用它。

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

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
    }

【问题讨论】:

  • guard let address = address as? String else { return } 你可能想做completion(nil) 以防地址不好,但这很奇怪,因为address 不应该是可选的。 placemarks 是零吗? geocodeAddressString()中触发了哪种情况?
  • 对不起,我不太明白。如果位置无法解析,我确实有完成(无)。
  • 知道了。我在上面的问题中添加了功能和解释。

标签: swift completionhandler


【解决方案1】:

我的猜测(这只是一个猜测)是你使用了这个表达式但不明白它的含义:

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

认为你的意思可能是:

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

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

【讨论】:

  • 好的,我现在知道你的意思了。对我来说有点像管灯的时刻。我刚开始学习 Swift 3 个月前。谢谢,帮了大忙。
  • 是的,case 模式语法真的很糟糕。
猜你喜欢
  • 1970-01-01
  • 2020-01-16
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多