在 swift 中使用 Google place api 时出错

问题描述

我正在使用 google place api 在我的 swift 应用程序中获取位置。在我的应用程序中,当我要通过单击 tableview 单元格内的文本字段来放置 api 屏幕时,它工作正常。但是,当我使用相同的代码通过单击 uiview 中存在的文本字段来显示地点 api 屏幕时,在选择任何地点后,它会返回到上一个屏幕,但地点 api 屏幕再次自动打开。我已经添加了我的代码,任何人都可以看到它并告诉我解决方案吗?

import GooglePlaces

class AddPatientViewController: UIViewController{
   
    //MARK:- Properties
    @IBOutlet weak var location_TextField: UITextField!
  
    
    //MARK:- Variables
    
    var locationManager = CLLocationManager()
    var mAppDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate;
    
    
    //MARK:- LifeCycles Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setDelegate()
     
        
    }

    
    
    
    //MARK:- Helpers
   
    private func setDelegate(){
       
        location_TextField.delegate = self 
       
  }
   
    
   
    
    //MARK: - getLocation
    
    func getCurrentLatLongFromCLlocation() {
        
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        
        
        if CLLocationManager.locationServicesEnabled() {
            switch CLLocationManager.authorizationStatus() {
            case .notDetermined,.restricted,.denied:
                print("No access")
                getPermissionAgain()
            case .authorizedAlways,.authorizedWhenInUse:
                print("Access")
                if let coordinateValue = locationManager.location?.coordinate {
                    
                    mAppDelegate.cordinateVal = coordinateValue
                    self.getPlaceDataUsingLocation()
                }
            @unkNown default:
                getPermissionAgain()
            }
        } else {
            print("Location services are not enabled")
            getPermissionAgain()
        }
        
        
    }
    
    func getPermissionAgain(){
        
        let alert = UIAlertController(title: "Simplr",message: "required location permission to set your search location",preferredStyle: .alert)
        let okayAction = UIAlertAction(title: "dismiss",style: .default,handler: nil)
        let settingsAction = UIAlertAction(title: "Settings",style: .default) { (action) in
            if let appSettings = URL(string: UIApplication.openSettingsURLString) {
                if #available(iOS 10.0,*) {
                    UIApplication.shared.open(appSettings,options: [:],completionHandler: { (enabled) in
                        dispatchQueue.main.async {
                            
                            //UIApplication.shared.registerForRemoteNotifications()
                            
                        }
                        
                    })
                } else {
                    // Fallback on earlier versions
                }
            }
        }
        alert.addAction(okayAction)
        alert.addAction(settingsAction)
        present(alert,animated: false,completion: nil)
        
    }
    
    
    func getPlaceDataUsingLocation(){
        
        dispatchQueue.global().async {
            
            // Specify the place data types to return.
            let placesClient = GMSPlacesClient.init()
            
            let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
                                                        UInt(GMSPlaceField.placeID.rawValue) | UInt(GMSPlaceField.coordinate.rawValue) | UInt(GMSPlaceField.formattedAddress.rawValue))
            
            placesClient.currentPlace { (list,error) in
                
                if let error = error {
                    print("An error occurred: \(error.localizedDescription)")
                    return
                }
                
                if let placeLikelihoodList = list?.likelihoods {
                    for likelihood in placeLikelihoodList {
                        let place = likelihood.place
                        print("\n\n")
                        print("Current Place name \(String(describing: place.name)) at likelihood \(likelihood.likelihood)")
                        print("Current PlaceID \(String(describing: place.placeID))")
                        print("Formatted Address: \(String(describing: place.formattedAddress))")
                        //                    print("Fields: \(place.)")
                        print("\nAddress Component: \(String(describing: place.addressComponents))\n")
                        print("Type: \(String(describing: place.types))")
                        
                    }
                }
                
                
            }
            
            
        }
        
        
    }
   
}



//MARK: - UITextfield Delegate Methods


    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{
      
        if textField == location_TextField{
            let autocompleteController = GMSAutocompleteViewController()
            autocompleteController.delegate = self
//            autocompleteController.primaryTextColor = UIColor(hex: "#4C2B6D")
//            autocompleteController.secondaryTextColor = UIColor(hex: "#4C2B6D")
            
            // Specify the place data types to return.
            let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
                UInt(GMSPlaceField.placeID.rawValue) | UInt(GMSPlaceField.coordinate.rawValue) |
                UInt(GMSPlaceField.formattedAddress.rawValue) | UInt(GMSPlaceField.addressComponents.rawValue))
            
            autocompleteController.placeFields = fields
            autocompleteController.navigationController?.navigationBar.barTintColor = .blue
            autocompleteController.navigationController?.navigationBar.prefersLargeTitles = true
            // Specify a filter.
            let filter = GMSAutocompleteFilter()
            filter.type = .geocode
            autocompleteController.autocompleteFilter = filter
            
            // display the autocomplete view controller.
            autocompleteController.modalPresentationStyle = .fullScreen
            present(autocompleteController,animated: true,completion: nil)
        }
        return true
    }
    
   
}

//MARK: - GMSAutocompleteViewControllerDelegate

@available(iOS 13.0,*)
extension AddPatientViewController: GMSAutocompleteViewControllerDelegate {
    
    // Handle the user's selection.
    func viewController(_ viewController: GMSAutocompleteViewController,didAutocompleteWith place: GMSPlace) {

        print("selected place is \(getFormattedAddressFromAddressComponents(place: place))")
        location_TextField.text = getFormattedAddressFromAddressComponents(place: place)
        self.dismiss(animated: true)
    }
    
    func viewController(_ viewController: GMSAutocompleteViewController,didFailAutocompleteWithError error: Error) {
        // Todo: handle the error.
        print("Error: ",error.localizedDescription)
    }
    
    // User canceled the operation.
    func wasCancelled(_ viewController: GMSAutocompleteViewController) {
        self.dismiss(animated: true)
    }
    
    // Turn the network activity indicator on and off again.
    func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
    
    func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
    
    func getFormattedAddressFromAddressComponents(place: GMSPlace) -> String{
        
        var neighborhood = ""
        var locality = ""
        var sublocality = ""
        var administrative_area_level_1 = ""
        
        var formatedAddress = ""
       

        if let addressComponents : Array<GMSAddressComponent> = place.addressComponents{
            print(addressComponents)
            
            for component in addressComponents{
                
                if component.types.contains("administrative_area_level_1"){
                    
                    if let shortName = component.shortName{
                        
                        administrative_area_level_1 = shortName

                    }
                    
                }
                else if component.types.contains("neighborhood")
                {
                    
                    neighborhood = component.name
                    
                } else if component.types.contains("sublocality")
                {
                    
                    sublocality = component.name
                        
                  
                }else if component.types.contains("locality")
                {
                    
                    locality = component.name
                }

                
            }
            
            var shouldAddComma = false
            
            if !isNullObject(anyObject: administrative_area_level_1){

                shouldAddComma = true
                
            }

            if !isNullObject(anyObject: neighborhood){
                
                formatedAddress = neighborhood
                
            }else if !isNullObject(anyObject: sublocality){
                
                formatedAddress = sublocality
            }
            else if !isNullObject(anyObject: locality){
                
                formatedAddress = locality
            }
            
            
            if !isNullObject(anyObject: formatedAddress){
                
                if shouldAddComma{
                    
                    formatedAddress = "\(formatedAddress),\(administrative_area_level_1)"
                }
            }
        }
        
        return formatedAddress

    }
    
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)