forked from USDepartmentofLabor/Swift-Federal-Data-SDK
-
Notifications
You must be signed in to change notification settings - Fork 1
/
GovDataRequest.swift
executable file
·165 lines (143 loc) · 6.48 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
//
// 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, NSURLSessionDelegate {
var delegate: GovDataRequestProtocol? = nil
var APIKey = ""
var APIHost = ""
var APIURL = ""
var responseFormat = "JSON"
var timeOut = 60.0
let URL_API_V1 = "http://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
println("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:
println("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 count(queryString) == 0 {
queryString += "?" + argKey + "=" + argValue + "&apiKey=" + APIKey
} else {
queryString += "&" + argKey + "=" + argValue
}
default:
if count(queryString) == 0 {
queryString += "?" + argKey + "=" + argValue
} else {
queryString += "&" + argKey + "=" + argValue
}
}
}
//If there are arguments, append them to the url
if count(queryString) > 0 {
url += queryString
}
//DOT FMCSA requires that the key be placed at the end.
if APIHost == "https://mobile.fmcsa.dot.gov" {
if count(queryString) > 0 {
url += "&webKey=" + APIKey
} else {
url += "?webKey=" + APIKey
}
}
// Send the request to the API and parse
var urlToPackage = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
println(urlToPackage)
var urlToSend: NSURL = NSURL(string: urlToPackage!)!
var apiSessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
apiSessionConfiguration.timeoutIntervalForRequest = timeOut
var session = NSURLSession(configuration: apiSessionConfiguration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
var request = NSMutableURLRequest(URL:urlToSend)
request.addValue("application/json",forHTTPHeaderField:"Accept")
if (APIHost == URL_API_V2) {
request.addValue(APIKey, forHTTPHeaderField: "X-API-KEY")
}
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Task completed")
if((error) != nil) {
// if there is an error in the request, print it to the console
self.delegate?.didCompleteWithError(error.localizedDescription)
//println(error.localizedDescription)
println("oops!")
}
var err: NSError?
if self.responseFormat == "JSON" {
if let jsonResult: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) {
if(err != nil) {
// If there is an error parson JSON, print it to the console
NSLog ("Error parsing the JSON")
}
if jsonResult is NSDictionary {
self.delegate?.didCompleteWithDictionary(jsonResult as! NSDictionary)
}
else if jsonResult is NSArray {
self.delegate?.didCompleteWithArray(jsonResult as! NSArray)
}
else {
//return Object
self.delegate?.didComplete(jsonResult as! NSString)
}
}
} else if self.responseFormat == "XML" {
//let parser = SWXMLHash()
var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
let xml = SWXMLHash.parse(data)
self.delegate?.didCompleteWithXML(xml)
}
})
task.resume()
}
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))
}
}