-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUdacityClient.swift
More file actions
336 lines (275 loc) · 15.2 KB
/
UdacityClient.swift
File metadata and controls
336 lines (275 loc) · 15.2 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//
// UdacityClient.swift
// OnTheMap
//
// Created by Craig Vanderzwaag on 11/25/15.
// Copyright © 2015 blueHula Studios. All rights reserved.
//
import Foundation
import FBSDKCoreKit
import FBSDKLoginKit
import Reachability
class UdacityClient: NSObject {
var isReachable: Bool?
var baseURL: String? = nil
/* Facebook Access Token */
var accessToken: String? = nil
/* Shared session */
var session: NSURLSession
/* Authentication state */
var sessionID : String? = nil
var userID : String? = nil
var udacityUser : StudentInfo? = nil
override init() {
session = NSURLSession.sharedSession()
super.init()
}
//MARK: Network Connection
func checkNetworkConnection() {
let reachability: Reachability
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return
}
reachability.whenReachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
if reachability.isReachableViaWiFi() {
self.isReachable = true
print("Reachable via WiFi")
} else {
self.isReachable = true
print("Reachable via Cellular")
}
}
}
reachability.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
self.isReachable = false
print("Not reachable")
}
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
func taskForGETMethod(method: String, parameters: [String : AnyObject], completionHandler: (result: AnyObject!, error: NSError?) -> Void) -> NSURLSessionDataTask {
//Check if we're calling Udacity or Parse API and assigning associated URL
if (method.containsString(UdacityClient.ParameterKeys.api)){
baseURL = UdacityClient.Constants.UdacityBaseURLSecure
}
else{
baseURL = UdacityClient.Constants.ParseBaseURLSecure
}
//Build the URL and configure the request
let urlString = baseURL! + method + UdacityClient.escapedParameters(parameters)
let url = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
if (method.containsString(UdacityClient.ParameterKeys.api)){
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
}else{
request.addValue(UdacityClient.Constants.ParseAppID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(UdacityClient.Constants.ParseAPIKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
}
// Perform GET with Completion options and error/response handling
let task = session.dataTaskWithRequest(request) { (data, response, error) in
// Was there an error?
guard (error == nil) else {
let userInfo = [NSLocalizedDescriptionKey : error!.localizedDescription]
completionHandler(result: false, error: NSError(domain: "taskForGetMethod", code: 1, userInfo: userInfo))
return
}
//Did we get a sucessful 2XX response?
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else {
if let response = response as? NSHTTPURLResponse {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response! Status code: \(response.statusCode)!"]
completionHandler(result: false, error: NSError(domain: "taskForGetMethod", code: 1, userInfo: userInfo))
} else if let response = response {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response! Response: \(response)!"]
completionHandler(result: false, error: NSError(domain: "taskForGetMethod", code: 1, userInfo: userInfo))
} else {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response!"]
completionHandler(result: false, error: NSError(domain: "taskForGetMethod", code: 1, userInfo: userInfo))
}
return
}
//Was there any data returned?
guard let data = data else {
let userInfo = [NSLocalizedDescriptionKey : "No data was returned by the request!"]
completionHandler(result: false, error: NSError(domain: "taskForGetMethod", code: 1, userInfo: userInfo))
return
}
//Pass Data to parse method for parsing
UdacityClient.parseJSONWithCompletionHandler(data, completionHandler: completionHandler)
}
//Start the request
task.resume()
return task
}
func taskForPOSTMethod(method: String, parameters: [String : AnyObject], jsonBody: [String:AnyObject], completionHandler: (result: AnyObject!, error: NSError?) -> Void) -> NSURLSessionDataTask {
//Check if we're calling Udacity or Parse API and assigning associated URL
if (method.containsString(UdacityClient.ParameterKeys.api)){
baseURL = UdacityClient.Constants.UdacityBaseURLSecure
}
else{
baseURL = UdacityClient.Constants.ParseBaseURLSecure
}
//Build the URL and configure the request
let urlString = baseURL! + method + UdacityClient.escapedParameters(parameters)
let url = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
if (method.containsString("classes")){
request.addValue(UdacityClient.Constants.ParseAppID, forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue(UdacityClient.Constants.ParseAPIKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
}
else{
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
}
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonBody, options: .PrettyPrinted)
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Fetch failed: \((error as NSError).localizedDescription)"]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
}
// Perform POST with Completion options and error/response handling
let task = session.dataTaskWithRequest(request) { (data, response, error) in
guard (error == nil) else {
let userInfo = [NSLocalizedDescriptionKey : error!.localizedDescription]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
return
}
//Did we get a sucessful 2XX response?
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else {
if let response = response as? NSHTTPURLResponse {
if response.statusCode == 403{
let userInfo = [NSLocalizedDescriptionKey : "Invalid Username or Password"]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
}else if response.statusCode == 400{
let userInfo = [NSLocalizedDescriptionKey : "Failed to Post User Data"]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
}
else{
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response! Status code: \(response.statusCode)!"]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
}
} else if let response = response {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response! Response: \(response)!"]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
} else {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response!"]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
}
return
}
//Was there any data returned?
guard let data = data else {
let userInfo = [NSLocalizedDescriptionKey : "No data was returned by the request!"]
completionHandler(result: false, error: NSError(domain: "taskForPostMethod", code: 1, userInfo: userInfo))
return
}
//Pass Data to parse method for parsing
UdacityClient.parseJSONWithCompletionHandler(data, completionHandler: completionHandler)
}
//Start the request
task.resume()
return task
}
func taskForDeleteMethod(method: String, completionHandler: (result: AnyObject?, error: NSError?) -> Void) {
//Build the URL and configure the request
baseURL = UdacityClient.Constants.UdacityBaseURLSecure
let urlString = baseURL! + method
let url = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "DELETE"
var xsrfCookie: NSHTTPCookie? = nil
let sharedCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in sharedCookieStorage.cookies! as [NSHTTPCookie] {
if cookie.name == "XSRF-TOKEN" { xsrfCookie = cookie }
}
if let xsrfCookie = xsrfCookie {
request.setValue(xsrfCookie.value, forHTTPHeaderField: "X-XSRF-TOKEN")
}
// Perform DELETE with Completion options and error/response handling
let task = session.dataTaskWithRequest(request) { (data, response, error) in
guard (error == nil) else {
let userInfo = [NSLocalizedDescriptionKey : error!.localizedDescription]
completionHandler(result: false, error: NSError(domain: "taskForDeleteMethod", code: 1, userInfo: userInfo))
return
}
//Did we get a sucessful 2XX response?
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else {
if let response = response as? NSHTTPURLResponse {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response! Status code: \(response.statusCode)!"]
completionHandler(result: false, error: NSError(domain: "taskForDeleteMethod", code: 1, userInfo: userInfo))
} else if let response = response {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response! Response: \(response)!"]
completionHandler(result: false, error: NSError(domain: "taskForDeleteMethod", code: 1, userInfo: userInfo))
} else {
let userInfo = [NSLocalizedDescriptionKey : "Your request returned an invalid response!"]
completionHandler(result: false, error: NSError(domain: "taskForDeleteMethod", code: 1, userInfo: userInfo))
}
return
}
//Was there any data returned?
guard let data = data else {
let userInfo = [NSLocalizedDescriptionKey : "No data was returned by the request!"]
completionHandler(result: false, error: NSError(domain: "taskForDeleteMethod", code: 1, userInfo: userInfo))
return
}
//Pass Data to parse method for parsing
UdacityClient.parseJSONWithCompletionHandler(data, completionHandler: completionHandler)
}
//Start the request
task.resume()
}
/* Helper: Given raw JSON, return a usable Foundation object */
class func parseJSONWithCompletionHandler(data: NSData, completionHandler: (result: AnyObject!, error: NSError?) -> Void) {
var parsedResult: AnyObject!
do {
if (UdacityClient.sharedInstance().baseURL!.containsString(UdacityClient.JSONBodyKeys.UCBodyHeader)){
parsedResult = try NSJSONSerialization.JSONObjectWithData(data.subdataWithRange(NSMakeRange(5, data.length - 5)), options: .AllowFragments)}
else{
parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
}
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the received data"]
completionHandler(result: nil, error: NSError(domain: "parseJSONWithCompletionHandler", code: 1, userInfo: userInfo))
}
completionHandler(result: parsedResult, error: nil)
}
/* Helper function: Given a dictionary of parameters, convert to a string for a url */
class func escapedParameters(parameters: [String : AnyObject]) -> String {
var urlVars = [String]()
for (key, value) in parameters {
let stringValue = "\(value)"
let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
urlVars += [key + "=" + "\(escapedValue!)"]
}
return (!urlVars.isEmpty ? "?" : "") + urlVars.joinWithSeparator("&")
}
class func subtituteKeyInMethod(method: String, key: String, value: String) -> String? {
if method.rangeOfString("{\(key)}") != nil {
return method.stringByReplacingOccurrencesOfString("{\(key)}", withString: value)
} else {
return nil
}
}
class func sharedInstance() -> UdacityClient {
struct Singleton {
static var sharedInstance = UdacityClient()
}
return Singleton.sharedInstance
}
}