Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set text in GMSAutocompleteViewController in Google Place AutocompleteViewController

I need help to set text in searchBar of GMSAutocompleteViewController when open in my App. I am using GMSAutocompleteViewController in Google Place AutocompleteViewController.

enter image description here

like image 227
Nalawala Murtuza Avatar asked Dec 29 '16 14:12

Nalawala Murtuza


1 Answers

I got a working solution by combining @Youngjin and @Exception's answers for Swift 4 and Google Places 2.6.0

To access the GMSAutocompleteViewController searchbar:

let views = gmsAutoCompleteViewController.view.subviews
let subviewsOfSubview = views.first!.subviews
let subOfNavTransitionView = subviewsOfSubview[1].subviews
let subOfContentView = subOfNavTransitionView[2].subviews     
let searchBar = subOfContentView[0] as! UISearchBar

Then to set the text and also search automatically:

searchBar.text = "Your address"
searchBar.delegate?.searchBar?(searchBar, textDidChange: "Your address") // This performs the automatic searching.

I found that I received a EXC_BAD_ACCESS error when attempting to set the text from within didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController).

So I instead put this code in the completion block where I present the autoCompleteController, which works without issue.

Combining it all together:

let gmsAutoCompleteViewController = GMSAutocompleteViewController()
gmsAutoCompleteViewController.delegate = self

present(gmsAutoCompleteViewController, animated: true) {
    let views = gmsAutoCompleteViewController.view.subviews
    let subviewsOfSubview = views.first!.subviews
    let subOfNavTransitionView = subviewsOfSubview[1].subviews
    let subOfContentView = subOfNavTransitionView[2].subviews
    let searchBar = subOfContentView[0] as! UISearchBar
    searchBar.text = "Your address"
    searchBar.delegate?.searchBar?(searchBar, textDidChange: "Your address")
}

EDIT: I found that this solution only seems to work on iOS 11. let searchBar = subOfContentView[0] as! UISearchBar will fail on iOS 10, and possibly lower versions.

like image 159
Dafurman Avatar answered Sep 24 '22 10:09

Dafurman