shade27
shade27

Reputation: 75

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.

Upvotes: 0

Views: 650

Answers (2)

shade27
shade27

Reputation: 75

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

Upvotes: 0

DoN1cK
DoN1cK

Reputation: 615

Mapbox search ui done in UIKit and you can wrap any UIView or UIViewController with UIViewRepresentable or UIViewControllerRepresentable.

Here is an example:

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

Upvotes: 1

Related Questions