iOS SwiftUI 上的 Mapbox 自动完成功能

Mapbox autocomplete feature on iOS SwiftUI

我正在开发一个基于 swift UI 的 iOS 应用程序。我想在其中添加 Mapbox 自动完成功能。我尝试集成 mapbox-search-SDK 但它似乎不支持 swift UI.

有什么我可以做的吗?这可能吗?我也不可能恢复到另一个地图提供商。提前致谢。

Mapbox 搜索 ui 在 UIKit 中完成,您可以用 UIViewRepresentableUIViewControllerRepresentable.

包装任何 UIViewUIViewController

这是一个例子:

struct SearchControllerView: UIViewControllerRepresentable {
    typealias UIViewControllerType = MapboxSearchController

    func makeUIViewController(context: Context) -> MapboxSearchController{
        MapboxSearchController()
    }
    func updateUIViewController(_ uiViewController: MapboxSearchController, context: Context) { }
}

struct SearchControllerView_Previews: PreviewProvider {
    static var previews: some View {
        SearchControllerView()
    }
}

显然对于 SwiftUI,您必须使用 Mapbox Geocoding API 自行构建自动完成搜索功能。我做了个简单的,如下图

import SwiftUI
import Alamofire

struct AutocompleteSheet: View {

    @State var searchText = ""
    @State var SearchResults:[data]? = nil

 var body: some View {

        ScrollView {
         
            HStack {
              TextField(" Search locations", text: $searchText)
                }
                .onChange(of: searchText, perform: { value in
                    AutocompleteAPI()
                })
             }

if SearchResults != nil {
                    
ForEach(0..<SearchResults!.count, id: \.self) { index in

  HStack {
      Button(action: {
         print("which location: \(index)")
          }) {
                                        
          Image(systemName: "mappin.and.ellipse")
              .foregroundColor(Color(.systemGray2))

          Text("\(SearchResults![index].name)")
       }
      }
     }
    }
   }
  }
 
func AutocompleteAPI() -> Void {
    
    let parameters:Parameters = [:]
    
    APIClient.Autocomplete(query : searchText, completion:{(result) in
        switch(result){
        
        case .success(let Details):
            
            print(Details)
            
            if (Details.meta.statusCode == 200) {
                
                print("Successful")
                SearchResults = Details.data
            }
            else{
                
                print("Fail")
            }
            
        case .failure(let error):
            print("ERROR",error)
        }
    })
  }
}