Search code examples
iosswiftuisdkmapboxmapbox-ios

Mapbox autocomplete feature on iOS SwiftUI


I'm developing an iOS app based on swift UI. I want to have the Mapbox autocomplete feature in it. I tried integrating the mapbox-search-SDK but it doesn't seem to support swift UI.

Is there anything I could do? Is this something possible? There's no possibility for me to revert back to another map provider either. Thanks in advance.


Solution

  • Apparently for SwiftUI, you'll have to build the Autocomplete search feature on your own by using Mapbox Geocoding API. I made something simple, as shown below.

    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)
            }
        })
      }
    }