如何在swiftui中使用completionHandler响应? [英] How to use completionHandler response in swiftui?

查看:29
本文介绍了如何在swiftui中使用completionHandler响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 swiftui 应用程序中,我根据搜索栏检索地址.对于每个地址,我想检索用户位置和地址之间的距离.所以我创建了一个函数(它返回一个字符串),我直接在 swiftui 的文本组件中调用它.但是答案来自一个completionHandler,我不知道如何在text()中得到这种答案.

In a swiftui application, I retrieve addresses based on a search bar. For each address, I want to retrieve the distance between the user's location and the address. So I created a function (which returns a string) that I call directly in a text component of swiftui. But the answer comes from a completionHandler, and I don't know how to get this kind of answer in a text().

以字符串形式返回距离的函数:

Function that return distance in string:

func getDistance(placeMarkLocation: MKLocalSearchCompletion, currentLocation: CLLocation, completionHandler: @escaping (String) -> ()) {
  let searchRequest = MKLocalSearch.Request(completion: placeMarkLocation)
  let search = MKLocalSearch(request: searchRequest)
  var placeMarkCoordinates: CLLocation = CLLocation(latitude: 0, longitude: 0)
        
  search.start { (response, error) in
    guard let coordinate = response?.mapItems[0].placemark.coordinate else {
      return
    }

    placeMarkCoordinates = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
      
    completionHandler("\(currentLocation.distance(from: placeMarkCoordinates).getDistanceString)")
  }
}

ForEach(locationSearchService.searchResults.indices, id: \.self) { index in
  HStack(spacing: 5) {
    VStack(alignment: .leading, spacing: 2) {
      TextWithAttributedString(attributedString: self.highlightedText(
        text: locationSearchService.searchResults[index].title,
        inRanges: locationSearchService.searchResults[index].titleHighlightRanges,
        size: 20.0
      ) as! NSMutableAttributedString, dynamicHeight: $height)
        .frame(minHeight: height)
        .fixedSize(horizontal: false, vertical: true)                                   
      }
      .frame(minWidth: 0, maxWidth: geometry.size.width)
      .padding(.leading, 15)
      .padding(.top, 10)
      .padding(.bottom, index + 1 == locationSearchService.searchResults.count ? 20 : 10)

      Spacer()
      
      // No work          
      Text("\(self.getDistance(placeMarkLocation: locationSearchService.searchResults[index], currentLocation: CLLocation(latitude: 47.2102877, longitude: -1.5692436)) { value in value })")
        .foregroundColor(Color.gray)
        .padding(.trailing, 15)
        .padding(.top, index == 0 ? 20 : 10)
        .padding(.bottom, index + 1 == locationSearchService.searchResults.count ? 20 : 10)
    }
  }
}       

推荐答案

您可以创建一个将搜索结果 (locationSearchService.searchResults[index]) 作为参数的子视图.其目的是显示计算出的距离.当这个(每个)子视图出现(onAppear)时,可以执行计算距离的函数(getDistance).并且完成处理程序会更新这个子视图的状态.

You could create a subview that would take a search result (locationSearchService.searchResults[index]) as a parameter. And whose purpose would be to display the calculated distance. The function that calculates the distance (getDistance) could be executed when this (each) subview appears (onAppear). And the completion handler would update the state of this subview.

struct DistanceView: View {
    @State private var distance: String?
    let placeMarkLocation: MKLocalSearchCompletion
    var body: some View {
        Text(distance ?? "getting distance")
            .onAppear {
                getDistance(placeMarkLocation: placeMarkLocation, currentLocation: CLLocation(latitude: 47.2, longitude: -1.5)) { value in
                    distance = value
                }
            }
    }
}

这篇关于如何在swiftui中使用completionHandler响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆