/
ViewController.swift
124 lines (107 loc) · 5.26 KB
/
ViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
//
// ViewController.swift
// AutocompleteTextfieldSwift
//
// Created by Mylene Bayan on 2/21/15.
// Copyright (c) 2015 mnbayan. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var autocompleteTextfield: AutoCompleteTextField!
private var responseData:NSMutableData?
private var selectedPointAnnotation:MKPointAnnotation?
private var dataTask:NSURLSessionDataTask?
private let googleMapsKey = "AIzaSyDg2tlPcoqxx2Q2rfjhsAKS-9j0n3JA_a4"
private let baseURLString = "https://maps.googleapis.com/maps/api/place/autocomplete/json"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configureTextField()
handleTextFieldInterfaces()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func configureTextField(){
autocompleteTextfield.autoCompleteTextColor = UIColor(red: 128.0/255.0, green: 128.0/255.0, blue: 128.0/255.0, alpha: 1.0)
autocompleteTextfield.autoCompleteTextFont = UIFont(name: "HelveticaNeue-Light", size: 12.0)!
autocompleteTextfield.autoCompleteCellHeight = 35.0
autocompleteTextfield.maximumAutoCompleteCount = 20
autocompleteTextfield.hidesWhenSelected = true
autocompleteTextfield.hidesWhenEmpty = true
autocompleteTextfield.enableAttributedText = true
var attributes = [String:AnyObject]()
attributes[NSForegroundColorAttributeName] = UIColor.blackColor()
attributes[NSFontAttributeName] = UIFont(name: "HelveticaNeue-Bold", size: 12.0)
autocompleteTextfield.autoCompleteAttributes = attributes
}
private func handleTextFieldInterfaces(){
autocompleteTextfield.onTextChange = {[weak self] text in
if !text.isEmpty{
if let dataTask = self?.dataTask {
dataTask.cancel()
}
self?.fetchAutocompletePlaces(text)
}
}
autocompleteTextfield.onSelect = {[weak self] text, indexpath in
Location.geocodeAddressString(text, completion: { (placemark, error) -> Void in
if let coordinate = placemark?.location?.coordinate {
self?.addAnnotation(coordinate, address: text)
self?.mapView.setCenterCoordinate(coordinate, zoomLevel: 12, animated: true)
}
})
}
}
//MARK: - Private Methods
private func addAnnotation(coordinate:CLLocationCoordinate2D, address:String?){
if let annotation = selectedPointAnnotation{
mapView.removeAnnotation(annotation)
}
selectedPointAnnotation = MKPointAnnotation()
selectedPointAnnotation!.coordinate = coordinate
selectedPointAnnotation!.title = address
mapView.addAnnotation(selectedPointAnnotation!)
}
private func fetchAutocompletePlaces(keyword:String) {
let urlString = "\(baseURLString)?key=\(googleMapsKey)&input=\(keyword)"
let s = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
s.addCharactersInString("+&")
if let encodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(s) {
if let url = NSURL(string: encodedString) {
let request = NSURLRequest(URL: url)
dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if let data = data{
do{
let result = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let status = result["status"] as? String{
if status == "OK"{
if let predictions = result["predictions"] as? NSArray{
var locations = [String]()
for dict in predictions as! [NSDictionary]{
locations.append(dict["description"] as! String)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.autocompleteTextfield.autoCompleteStrings = locations
})
return
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.autocompleteTextfield.autoCompleteStrings = nil
})
}
catch let error as NSError{
print("Error: \(error.localizedDescription)")
}
}
})
dataTask?.resume()
}
}
}
}