This repository has been archived by the owner on Jan 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
GovDataRequest.swift
executable file
·191 lines (169 loc) · 7.69 KB
/
GovDataRequest.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
//
// GovDataRequest.swift
//
//
// Created by Michael Pulsifer (U.S. Department of Labor) on 6/18/14.
// License: Public Domain
//
import Foundation
protocol GovDataRequestProtocol {
func didCompleteWithError(errorMessage: String)
func didCompleteWithDictionary(results: NSDictionary)
func didCompleteWithXML(results:XMLIndexer)
func didCompleteWithArray(results: NSArray)
func didComplete(results: NSString)
}
class GovDataRequest : NSObject, URLSessionDelegate {
var delegate: GovDataRequestProtocol? = nil
var APIKey = ""
var APIHost = ""
var APIURL = ""
var responseFormat = "JSON"
var timeOut = 60.0
let URL_API_V1 = "https://api.dol.gov"
let URL_API_V2 = "https://data.dol.gov"
init(APIKey: String, APIHost: String, APIURL:String) {
self.APIKey = APIKey
self.APIHost = APIHost
self.APIURL = APIURL
}
func callAPIMethod (method: String, arguments: Dictionary<String,String>) {
// Construct the base url based on the provided information
var url = APIHost + APIURL + "/" + method
// Start building the query string
var queryString = ""
// Where appropriate, add the key
switch APIHost {
case URL_API_V1:
queryString = "?KEY=" + APIKey
case URL_API_V2:
queryString = ""
case "http://api.census.gov", "http://pillbox.nlm.nih.gov":
queryString = "?key=" + APIKey
case "http://api.eia.gov", "http://developer.nrel.gov", "http://api.stlouisfed.org", "http://healthfinder.gov":
queryString = "?api_key=" + APIKey
case "http://www.ncdc.noaa.gov":
queryString = "?token=" + APIKey
default:
// do nothing for now
print("doing nothing for now")
}
//Construct the arguments part of the query string
for (argKey, argValue) in arguments {
switch APIHost {
case URL_API_V1:
// DOL's V1 API has specific formatting requirements for arguments in the query string
switch argKey {
case "top", "skip", "select", "orderby", "filter":
queryString += "&$" + argKey + "=" + argValue
case "format", "query", "region", "locality", "skipcount":
queryString += "&" + argKey + "=" + argValue
default:
print("nothing to see here")
}
case URL_API_V2:
queryString += "/" + argKey + "/" + argValue
case "http://go.usa.gov":
// go.usa.gov requires that the apiKey be the 2nd argument
if queryString == "" {
queryString += "?" + argKey + "=" + argValue + "&apiKey=" + APIKey
} else {
queryString += "&" + argKey + "=" + argValue
}
default:
if queryString == "" {
queryString += "?" + argKey + "=" + argValue
} else {
queryString += "&" + argKey + "=" + argValue
}
}
}
//If there are arguments, append them to the url
if queryString != "" {
url += queryString
}
//DOT FMCSA requires that the key be placed at the end.
if APIHost == "https://mobile.fmcsa.dot.gov" {
if queryString != "" {
url += "&webKey=" + APIKey
} else {
url += "?webKey=" + APIKey
}
}
// Send the request to the API and parse
var urlToPackage = url //.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(urlToPackage)
var urlToSend: NSURL = NSURL(string: urlToPackage)!
var apiSessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default
apiSessionConfiguration.timeoutIntervalForRequest = timeOut
//var session = URLSession(session: , didReceiveChallenge: self, completionHandler: OperationQueue.mainQueue()
var session = URLSession(configuration: apiSessionConfiguration, delegate: self, delegateQueue:OperationQueue.main)
var request = NSMutableURLRequest(url:urlToSend as URL)
request.addValue("application/json",forHTTPHeaderField:"Accept")
if (APIHost == URL_API_V2) {
request.addValue(APIKey, forHTTPHeaderField: "X-API-KEY")
}
var task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
print("Task completed")
if((error) != nil) {
// if there is an error in the request, print it to the console
self.delegate?.didCompleteWithError(errorMessage: (error?.localizedDescription)!)
//println(error.localizedDescription)
print("oops!")
}
var err: NSError?
print("*********")
print("About to try to parse")
print("*********")
if self.responseFormat == "JSON" {
// if let jsonResult: Any = JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) {
do {
if let jsonResult: Any = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) {
if(err != nil) {
// If there is an error parson JSON, print it to the console
NSLog ("Error parsing the JSON")
}
if jsonResult is NSDictionary {
print("*********")
print("Dictionary")
print("*********")
self.delegate?.didCompleteWithDictionary(results: jsonResult as! NSDictionary)
}
else if jsonResult is NSArray {
print("*********")
print("Array")
print("*********")
self.delegate?.didCompleteWithArray(results: jsonResult as! NSArray)
}
else {
print("*********")
print("Something else")
print("*********")
//return Object
self.delegate?.didComplete(results: jsonResult as! NSString)
}
}
} catch {
NSLog ("Error parsing the JSON")
}
} else if self.responseFormat == "XML" {
//let parser = SWXMLHash()
var dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
let xml = SWXMLHash.parse(data!)
self.delegate?.didCompleteWithXML(results: xml)
} else {
print("*********")
print("Neither JSON nor XML")
print("*********")
}
print("*********")
print("Outside the if")
print("*********")
})
task.resume()
}
/* private func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.UseCredential, URLCredential(forTrust: challenge.protectionSpace.serverTrust))
}
*/
}