2017-03-16 87 views
1

我試圖在我的應用程序中實現自動完成功能。Google API自動完成

我已經設置了一個按鈕的視圖控制器,並添加了下面的代碼。

不過,我不斷收到以下錯誤:

Cannot assign value of type 'selectAddress' to type 'GMSAutocompleteViewControllerDelegate?'

在這條線:

autocompleteController.delegate = self

有誰知道這是爲什麼?

import Foundation 
import UIKit 
import GoogleMaps 
import GooglePlaces 

class selectAddress: UIViewController, UISearchBarDelegate { 

    // Present the Autocomplete view controller when the button is pressed. 
    @IBAction func autocompleteClicked(_ sender: UIButton) { 
     let autocompleteController = GMSAutocompleteViewController() 
     autocompleteController.delegate = self 
     self.present(autocompleteController, animated: true, completion: nil) 
    } 
} 

extension ViewController: GMSAutocompleteViewControllerDelegate { 

    // Handle the user's selection. 
    func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { 
     print("Place name: \(place.name)") 
     print("Place address: \(place.formattedAddress)") 
     print("Place attributions: \(place.attributions)") 
     dismiss(animated: true, completion: nil) 
    } 

    func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { 
     // TODO: handle the error. 
     print("Error: ", error.localizedDescription) 
    } 

    // User canceled the operation. 
    func wasCancelled(_ viewController: GMSAutocompleteViewController) { 
     dismiss(animated: true, completion: nil) 
    } 

    // 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 viewController(viewController: GMSAutocompleteViewController!, didFailAutocompleteWithError error: NSError!) { 
     // TODO: handle the error. 
     print("Error: ", error.description) 
    } 

} 

回答

1

要設置委託給self,這是一類selectAddress型的,但你必須將擴展符合GMSAutocompleteViewControllerDelegate協議是ViewController類型。如果您將其更改爲extension selectAddress: GMSAutocompleteViewControllerDelegate,您將被設置。

+0

謝謝,這是現貨 – MattBlack