-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddLocationVC.swift
283 lines (213 loc) · 10.3 KB
/
AddLocationVC.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//
// AddLocationVC.swift
// OnTheMap
//
// Created by Yeontae Kim on 6/6/17.
// Copyright © 2017 YTK. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class AddLocationVC: UIViewController {
let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
var alertController: UIAlertController?
var results: StudentInformation?
var mapString: String = ""
var website: String = ""
var latitude: Double = 0.0
var longitude: Double = 0.0
var manager = CLLocationManager()
lazy var geocoder = CLGeocoder()
var keyboardOnScreen = false
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var websiteTextField: UITextField!
@IBOutlet weak var debugTextLabel: UILabel!
@IBOutlet weak var findLocationButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
subscribeToNotification(.UIKeyboardWillShow, selector: #selector(keyboardWillShow))
subscribeToNotification(.UIKeyboardWillHide, selector: #selector(keyboardWillHide))
subscribeToNotification(.UIKeyboardDidShow, selector: #selector(keyboardDidShow))
subscribeToNotification(.UIKeyboardDidHide, selector: #selector(keyboardDidHide))
debugTextLabel.text = ""
// Activity Indicator Set up
activityIndicator.center = view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.color = UIColor.lightGray
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndicator)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromAllNotifications()
}
@IBAction func findLocationButtonPressed(_ sender: Any) {
userDidTapView(self)
/* GUARD: Is the location input empty? */
guard let mapString = locationTextField.text, !mapString.isEmpty else {
self.getAlertView(title: "Input Error", error: "Location information is empty!!!")
return
}
/* GUARD: Is the website input empty? */
guard let website = websiteTextField.text, !website.isEmpty else {
self.getAlertView(title: "Input Error", error: "URL information is empty!!!")
return
}
/* Validate URL input by user */
// validating url using regular expression (code below created based on the solution from http://urlregex.com/)
let regexp = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
guard let range = websiteTextField.text?.range(of:regexp, options: .regularExpression) else {
self.getAlertView(title: "Input Error", error: "Invalid URL...Please enter valid URL!!")
return
}
self.website = websiteTextField.text!.substring(with:range)
self.mapString = locationTextField.text!
// Update View
self.activityIndicator.startAnimating()
// Geocode Address String
geocoder.geocodeAddressString(self.mapString) { (placemarks, error) in
// Process Response
self.processResponse(withPlacemarks: placemarks, error: error)
}
}
private func getStudentInformation() -> StudentInformation {
let uniqueKey: String = UdacityClient.sharedInstance().key["uniqueKey"]!
let firstName: String = UdacityClient.sharedInstance().firstName
let lastName: String = UdacityClient.sharedInstance().lastName
let latitude: Double = self.latitude
let longitude: Double = self.longitude
let mediaURL: String = self.website
let mapString: String = self.mapString
return StudentInformation(dictionary: ["uniqueKey": uniqueKey, "firstName": firstName, "lastName": lastName, "latitude": latitude, "longitude": longitude, "mediaURL": mediaURL, "mapString": mapString])
}
// forward geocoding (code below created based on the solution from https://cocoacasts.com/forward-and-reverse-geocoding-with-clgeocoder-part-1/)
private func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
print("function called")
self.activityIndicator.stopAnimating()
if error != nil {
// Alert if geocoding fails
self.alertController = UIAlertController(title: "Geocoding Failed", message: "Please enter a valid address or check your Internet connection!!", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Dismiss", style: .cancel)
self.alertController!.addAction(okayAction)
self.present(self.alertController!, animated: true, completion: nil)
return
} else { // Geocoding sucessfully executed
var location: CLLocation?
if let placemarks = placemarks, placemarks.count > 0 {
location = placemarks.first?.location
}
if let location = location {
let coordinate = location.coordinate
self.latitude = coordinate.latitude
self.longitude = coordinate.longitude
if self.results?.uniqueKey != nil { // Data already exists
// Update existing data with new user input
self.results?.mapString = self.mapString
self.results?.latitude = self.latitude
self.results?.longitude = self.longitude
self.results?.mediaURL = self.website
} else {
// Create new Student Information and send it to LocationConfirmVC
self.results = getStudentInformation()
self.results?.mapString = self.mapString
self.results?.latitude = self.latitude
self.results?.longitude = self.longitude
self.results?.mediaURL = self.website
}
// Get the storyboard and LocationConfirmVC. Pass data to the VC
let storyboard = UIStoryboard (name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "LocationConfirmVC") as! LocationConfirmVC
controller.results = self.results!
self.navigationController?.pushViewController(controller,animated: true)
} else {
self.getAlertView(title: "No Matching Location Found", error: error as! String)
}
}
}
}
// MARK: - AddLocationVC: UITextFieldDelegate
extension AddLocationVC: UITextFieldDelegate {
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: Show/Hide Keyboard
func keyboardWillShow(_ notification: Notification) {
if !keyboardOnScreen {
view.frame.origin.y -= keyboardHeight(notification) - 80
}
}
func keyboardWillHide(_ notification: Notification) {
if keyboardOnScreen {
view.frame.origin.y = 0
}
}
func keyboardDidShow(_ notification: Notification) {
keyboardOnScreen = true
}
func keyboardDidHide(_ notification: Notification) {
keyboardOnScreen = false
}
private func keyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = (notification as NSNotification).userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height - 55
}
private func resignIfFirstResponder(_ textField: UITextField) {
if textField.isFirstResponder {
textField.resignFirstResponder()
}
}
@IBAction func userDidTapView(_ sender: AnyObject) {
resignIfFirstResponder(locationTextField)
resignIfFirstResponder(websiteTextField)
}
}
// MARK: - AddLocationVC (Configure UI)
private extension AddLocationVC {
func setUIEnabled(_ enabled: Bool) {
locationTextField.isEnabled = enabled
websiteTextField.isEnabled = enabled
findLocationButton.isEnabled = enabled
debugTextLabel.text = ""
debugTextLabel.isEnabled = enabled
// find location button alpha
if enabled {
findLocationButton.alpha = 1.0
} else {
findLocationButton.alpha = 0.5
}
}
func configureUI() {
// configure background gradient
let backgroundGradient = CAGradientLayer()
backgroundGradient.colors = [Constants.UI.LoginColorTop, Constants.UI.LoginColorBottom]
backgroundGradient.locations = [0.0, 1.0]
backgroundGradient.frame = view.frame
view.layer.insertSublayer(backgroundGradient, at: 0)
configureTextField(locationTextField)
configureTextField(websiteTextField)
}
func configureTextField(_ textField: UITextField) {
let textFieldPaddingViewFrame = CGRect(x: 0.0, y: 0.0, width: 13.0, height: 0.0)
let textFieldPaddingView = UIView(frame: textFieldPaddingViewFrame)
textField.leftView = textFieldPaddingView
textField.leftViewMode = .always
textField.backgroundColor = Constants.UI.GreyColor
textField.textColor = Constants.UI.BlueColor
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.white])
textField.tintColor = Constants.UI.BlueColor
textField.delegate = self
}
}
// MARK: - AddLocationVC (Notifications)
private extension AddLocationVC {
func subscribeToNotification(_ notification: NSNotification.Name, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: notification, object: nil)
}
func unsubscribeFromAllNotifications() {
NotificationCenter.default.removeObserver(self)
}
}