我想在我的项目中集成Google Places Autocomplete API,但我无法通过文档实现它,也无法获得Swift-3的一些可靠参考。有人可以帮忙吗?感谢。
答案 0 :(得分:2)
Swift 4,xCode 9
通常的http请求。更多详情:https://developers.google.com/places/ios-api/autocomplete
PodFile
target 'stackoverflow-44996568' do
use_frameworks!
pod 'Alamofire'
pod 'ObjectMapper'
end
GoogleAutocompleteJSONModel
import ObjectMapper
class GoogleAutocompleteJSONModel: Mappable, CustomStringConvertible {
public fileprivate(set) var placeId: String?
public fileprivate(set) var reference: String?
public fileprivate(set) var title: String?
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
title <- map["description"]
placeId <- map["place_id"]
reference <- map["reference"]
}
var description: String {
return "\(toJSON())"
}
}
网络
import Alamofire
import ObjectMapper
class Network {
class GoogleAPI {
class Map {
class var googleApiKey: String {
return "YOUR_KEY"
}
class func autocomplete(request: String) {
let url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=\(request)&components=country:us&key=\(googleApiKey)"
Alamofire.request(url)
.responseJSON { response in
if let json = response.result.value as? [String: Any] {
//print("JSON: \(json)")
let places = Array<GoogleAutocompleteJSONModel>(json: json["predictions"])
let autocomplete = places.flatMap{ $0.title}
print("!!!! \(autocomplete)")
}
}
}
}
}
}
扩展
import Foundation
extension Array where Element: Mappable {
init(json: Any?) {
self.init()
var result = [Element]()
if let array = json as? [[String: Any]] {
for item in array {
if let profile = Element(JSON: item) {
result.append(profile)
}
}
}
self = result
}
}
的ViewController
import UIKit
class ViewController: UIViewController {
weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let searchBar = UISearchBar(frame: CGRect(origin: CGPoint(x: 0, y: 20), size: CGSize(width: UIScreen.main.bounds.width, height: 40)))
searchBar.delegate = self
view.addSubview(searchBar)
self.searchBar = searchBar
}
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
Network.GoogleAPI.Map.autocomplete(request: searchText)
}
}
答案 1 :(得分:0)
您需要先通过pod在项目中安装google place SDK。
pod 'GooglePlacePicker'
您可以使用此代码通过pod安装googlePlaces。
答案 2 :(得分:0)
我还创建了一个简单的库,只是为了避免针对简单请求的各种第三方库和google框架。
要发出诸如Autocomplete
,ReverseGeo
,Place
信息或Draw
路径之类的Google api请求,您只需使用以下步骤:-
GoogleApiHelper
导入项目。GoogleApiHelper
GoogleApi.shared.initialiseWithKey("API_KEY")
var input = GInput()
input.keyword = "San francisco"
GoogleApi.shared.callApi(input: input) { (response) in
if let results = response.data as? [GApiResponse.Autocomplete], response.isValidFor(.autocomplete) {
//Enjoy the Autocomplete Api
} else { print(response.error ?? "ERROR") }
}