-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParseClient.swift
298 lines (259 loc) · 11.6 KB
/
ParseClient.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
//
// ParseClient.swift
// OnTheMap
//
// Created by Darren Leith on 16/02/2016.
// Copyright © 2016 Darren Leith. All rights reserved.
//
import Foundation
class ParseClient: NSObject {
//MARK:- properties
//shared singleton instance of the Parse Client
static let sharedInstance = ParseClient()
//current user logged in
var currentStudent: StudentInformation?
//student already posted to the map?
var studentAlreadyPosted: Bool? = false
//array of students
var students : [StudentInformation]?
//is the student already on the map
var onTheMap : Bool?
//NSURLSession variable
let session: NSURLSession
//MARK: - lifecycle method
override init() {
session = NSURLSession.sharedSession()
super.init()
}
//MARK: - get student location
func getStudentLocations(completionHandlerForGet: (result: AnyObject!, error: NSError?) -> Void) {
let methodParameters = ParseClient.Parameters.methodParameters
let request = NSMutableURLRequest(URL: NSURL(string: ParseClient.Methods.StudentLocationURL + escapedParameters(methodParameters))!)
request.addValue(ParseClient.Keys.ParseAppId, forHTTPHeaderField: ParseClient.HTTPParameters.ParseAppIDHeader)
request.addValue(ParseClient.Keys.ParseAPIKey, forHTTPHeaderField: ParseClient.HTTPParameters.ParseAPIKeyHeader)
request.HTTPMethod = "GET"
//create task
let task = session.dataTaskWithRequest(request) { data, response, error in
func sendError(error: String) {
print(error)
let userInfo = [NSLocalizedDescriptionKey : error]
completionHandlerForGet(result: nil, error: NSError(domain: "getStudentLocations", code: 1, userInfo: userInfo))
}
/* GUARD: Was there an error? */
guard (error == nil) else {
sendError("There was an error with your request: \(error)")
return
}
/* GUARD: Did we get a successful 2XX response? */
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else {
sendError("Your request returned a status code other than 2xx!")
return
}
/* GUARD: Was there any data returned? */
guard let data = data else {
sendError("No data was returned by the request!")
return
}
self.parseStudentLocation(data, completionHandler: completionHandlerForGet)
}
task.resume()
}
//MARK: - post a student location
func postStudentLocation(student: StudentInformation?, completionHandler:(completed: Bool?,errorString: String?) -> Void ) {
//validation
if let student = student {
if let uniqueKey = student.uniqueKey, firstName = student.firstName, lastName = student.lastName, mapString = student.mapString, mediaURL = student.mediaURL, latitude = student.latitude, longitude = student.longitude {
let request = NSMutableURLRequest(URL: NSURL(string: ParseClient.Methods.StudentLocationURL)!)
request.HTTPMethod = "POST"
request.addValue(ParseClient.Keys.ParseAppId, forHTTPHeaderField: ParseClient.HTTPParameters.ParseAppIDHeader)
request.addValue(ParseClient.Keys.ParseAPIKey, forHTTPHeaderField: ParseClient.HTTPParameters.ParseAPIKeyHeader)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = "{\"uniqueKey\" : \"\(uniqueKey)\", \"firstName\" : \"\(firstName)\", \"lastName\" : \"\(lastName)\",\"mapString\" : \"\(mapString)\", \"mediaURL\" : \"\(mediaURL)\", \"latitude\" : \(latitude), \"longitude\" : \(longitude)}".dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
if let error = error {
completionHandler(completed: false, errorString: error.localizedDescription)
return
}
if let data = data {
self.parsePostStudentLocation(data: data, completionHandler: completionHandler)
} else {
completionHandler(completed: false, errorString: "Unable to post student data")
}
};
task.resume()
}
}
}
//MARK: - overwrite a student location
func overwriteStudent(student: StudentInformation?, completionHandler: (completed: Bool?, errorString: String?) -> Void) {
if let student = student {
if let uniqueKey = student.uniqueKey, objectId = student.objectId, firstName = student.firstName, lastName = student.lastName, mapString = student.mapString, mediaURL = student.mediaURL, latitude = student.latitude, longitude = student.longitude {
let urlString = ParseClient.Methods.StudentLocationURL + objectId
if let url = NSURL(string: urlString){
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "PUT"
request.addValue(ParseClient.Keys.ParseAppId, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(ParseClient.Keys.ParseAPIKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = "{\"uniqueKey\": \"\(uniqueKey)\", \"firstName\": \"\(firstName)\", \"lastName\": \"\(lastName)\",\"mapString\": \"\(mapString)\", \"mediaURL\": \"\(mediaURL)\",\"latitude\": \(latitude), \"longitude\": \(longitude)}".dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request){
(data, response, error) in
if let error = error {
completionHandler(completed: false, errorString: error.localizedDescription)
return
}
if let data = data {
self.parseOverwriteRequest(data: data, completionHandler: completionHandler)
return
}else {
completionHandler(completed: false, errorString: "Error: Unable to overwrite")
return
}
}; task.resume()
} else {
completionHandler(completed: false, errorString: "Error: Unable to overwrite")
}
} else {
completionHandler(completed: false, errorString: "Error: Unable to overwrite")
}
} else {
completionHandler(completed: false, errorString: "Error: Unable to overwrite")
}
}
//MARK: - query a student
func queryForStudent(uniqueKey: String?, completionHandler:(data: StudentInformation?, errorString: String?) -> Void){
if let uniqueKey = uniqueKey {
let methodParameters = [
"where": "{\"uniqueKey\": \"\(uniqueKey)\"}"
]
let urlString = ParseClient.Methods.StudentLocationURL + escapedParameters(methodParameters)
if let url = NSURL(string: urlString) {
let request = NSMutableURLRequest(URL: url)
request.addValue(ParseClient.Keys.ParseAppId, forHTTPHeaderField: ParseClient.HTTPParameters.ParseAppIDHeader)
request.addValue(ParseClient.Keys.ParseAPIKey, forHTTPHeaderField: ParseClient.HTTPParameters.ParseAPIKeyHeader)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
if let error = error{
completionHandler(data: nil, errorString: error.localizedDescription)
return
}
if let data = data {
self.parseQueryRequest(data: data, completionHandler: completionHandler)
} else {
completionHandler(data: nil, errorString: "Unable to get user data")
}
};
task.resume()
}
}
}
//MARK: - delete a student
func deleteStudent(objectId: String?, completionHandler:(completed: Bool?,errorString: String?) -> Void ) {
if objectId == nil {
completionHandler(completed: false, errorString: "Invalid objectId")
}
if let objectId = objectId {
let urlString = ParseClient.Methods.StudentLocationURL + objectId
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.addValue(ParseClient.Keys.ParseAppId, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(ParseClient.Keys.ParseAPIKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.HTTPMethod = "DELETE"
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
if let error = error {
completionHandler(completed: false, errorString: error.localizedDescription)
return
}
completionHandler(completed: true, errorString: nil)
}; task.resume()
}
}
//MARK: - parse student location
func parseStudentLocation(data: NSData, completionHandler: (result: AnyObject!, error: NSError?) -> Void) {
var parsedStudentLocation: AnyObject!
do {
parsedStudentLocation = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String: AnyObject]
if let students = parsedStudentLocation["results"] as? [[String: AnyObject]] {
completionHandler(result: students, error: nil)
return
}
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Error retrieving the 'results' key"]
completionHandler(result: nil, error: NSError(domain: "parseStudentLocation", code: 1, userInfo: userInfo))
}
}
//MARK: - parse POST a student location
func parsePostStudentLocation(data data: NSData, completionHandler:(completed: Bool?,errorString: String?) -> Void) {
do{
if let parsedData =
try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String: AnyObject]{
if let _ = parsedData["objectId"] as? String {
completionHandler(completed: true, errorString: nil)
return
}
completionHandler(completed: false, errorString: "Unable to add location")
} else {
completionHandler(completed: false, errorString: "Unable to add location")
}
} catch _ as NSError{
completionHandler(completed: false, errorString: "Error adding location")
}
}
//MARK: - parse over-write a student location
func parseOverwriteRequest(data data: NSData, completionHandler: (completed: Bool?,errorString: String?) -> Void){
do{
if let parsedData =
try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String: AnyObject]{
if let _ = parsedData["updatedAt"] as? String{
completionHandler(completed: true, errorString: nil)
return
}
completionHandler(completed: false, errorString: "Unable to update")
return
}
} catch let error as NSError{
completionHandler(completed: false, errorString: error.localizedDescription)
}
}
//MARK: - parse query request
func parseQueryRequest(data data: NSData, completionHandler: (data: StudentInformation?, errorString: String?) -> Void){
do{
if let parsedData =
try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String: AnyObject]{
if let students = parsedData["results"] as? [[String: AnyObject]]{
if let student = students.first{
let studentToReturn = StudentInformation(dictionary: student)
completionHandler(data: studentToReturn, errorString: nil)
return
} else if students.isEmpty{
completionHandler(data: nil, errorString: nil)
return
}
} else {
completionHandler(data: nil, errorString: "Unable to retrieve student data")
}
} else {
completionHandler(data: nil, errorString: "Unable to retrieve student data")
}
} catch let error as NSError{
completionHandler(data: nil, errorString: error.localizedDescription)
}
}
//MARK: - create a URL from the parameters
func escapedParameters(parameters: [String : AnyObject]) -> String {
var urlVars = [String]()
for (key, value) in parameters {
/* Make sure that it is a string value */
let stringValue = "\(value)"
/* Escape it */
let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
/* FIX: Replace spaces with '+' */
let replaceSpaceValue = escapedValue!.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)
/* Append it */
urlVars += [key + "=" + "\(replaceSpaceValue)"]
}
return (!urlVars.isEmpty ? "?" : "") + urlVars.joinWithSeparator("&")
}
}