Skip to content
This repository was archived by the owner on Jan 24, 2024. It is now read-only.

Commit 3d0c681

Browse files
Added XML parsing using SWXMLHash
1 parent fecdac4 commit 3d0c681

File tree

8 files changed

+364
-26
lines changed

8 files changed

+364
-26
lines changed

GovDataRequest.swift

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import Foundation
1111
protocol GovDataRequestProtocol {
1212
func didCompleteWithError(errorMessage: String)
1313
func didCompleteWithDictionary(results: NSDictionary)
14+
func didCompleteWithXML(results:XMLIndexer)
1415
}
1516

1617
class GovDataRequest {
@@ -95,38 +96,39 @@ class GovDataRequest {
9596
}
9697
}
9798

98-
/*
99-
ASSUMPTION: data retrieved is in JSON format.
100-
TODO: consider situation when XML is received.
101-
*/
102-
103-
104-
if responseFormat == "JSON" {
105-
// Send the request to the API and parse the JSON
106-
var urlToPackage = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
107-
var urlToSend: NSURL = NSURL(string: urlToPackage)
108-
var apiSessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
109-
apiSessionConfiguration.timeoutIntervalForRequest = timeOut
110-
var session = NSURLSession(configuration:apiSessionConfiguration)
111-
var request = NSMutableURLRequest(URL:urlToSend)
112-
request.addValue("application/json",forHTTPHeaderField:"Accept")
113-
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
114-
if(error) {
115-
// if there is an error in the request, print it to the console
116-
self.delegate?.didCompleteWithError(error.localizedDescription)
117-
//println(error.localizedDescription)
118-
println("oops!")
119-
}
120-
var err: NSError?
99+
// Send the request to the API and parse
100+
var urlToPackage = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
101+
println(urlToPackage)
102+
var urlToSend: NSURL = NSURL(string: urlToPackage)
103+
var apiSessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
104+
apiSessionConfiguration.timeoutIntervalForRequest = timeOut
105+
var session = NSURLSession(configuration:apiSessionConfiguration)
106+
var request = NSMutableURLRequest(URL:urlToSend)
107+
request.addValue("application/json",forHTTPHeaderField:"Accept")
108+
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
109+
println("Task completed")
110+
if(error) {
111+
// if there is an error in the request, print it to the console
112+
self.delegate?.didCompleteWithError(error.localizedDescription)
113+
//println(error.localizedDescription)
114+
println("oops!")
115+
}
116+
var err: NSError?
117+
if self.responseFormat == "JSON" {
121118
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
122119
if(err?) {
123120
// If there is an error parson JSON, print it to the console
124121
NSLog ("Error parsing the JSON")
125122
}
126123
self.delegate?.didCompleteWithDictionary(jsonResult)
127-
})
128-
task.resume()
129-
}
124+
} else if self.responseFormat == "XML" {
125+
let parser = SWXMLHash()
126+
var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
127+
let xml = parser.parse(dataString)
128+
self.delegate?.didCompleteWithXML(xml)
129+
}
130+
})
131+
task.resume()
130132
}
131133

132134

SWXMLHash LICENSE

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
SWXMLHash License
2+
3+
Copyright (c) 2014 David Mohundro
4+
5+
Permission is hereby granted, free of charge, to any person obtaining
6+
a copy of this software and associated documentation files (the
7+
"Software"), to deal in the Software without restriction, including
8+
without limitation the rights to use, copy, modify, merge, publish,
9+
distribute, sublicense, and/or sell copies of the Software, and to
10+
permit persons to whom the Software is furnished to do so, subject to
11+
the following conditions:
12+
13+
The above copyright notice and this permission notice shall be
14+
included in all copies or substantial portions of the Software.
15+
16+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

SWXMLHash/Extensions.swift

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
//
2+
// Extensions.swift
3+
//
4+
// Copyright (c) 2014 David Mohundro
5+
//
6+
// Permission is hereby granted, free of charge, to any person obtaining a copy
7+
// of this software and associated documentation files (the "Software"), to deal
8+
// in the Software without restriction, including without limitation the rights
9+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
// copies of the Software, and to permit persons to whom the Software is
11+
// furnished to do so, subject to the following conditions:
12+
//
13+
// The above copyright notice and this permission notice shall be included in
14+
// all copies or substantial portions of the Software.
15+
//
16+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22+
// THE SOFTWARE.
23+
24+
import Foundation
25+
26+
extension XMLIndexer: LogicValue {
27+
func getLogicValue() -> Bool {
28+
switch self {
29+
case .Error:
30+
return false
31+
default:
32+
return true
33+
}
34+
}
35+
}

SWXMLHash/Info.plist

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>CFBundleDevelopmentRegion</key>
6+
<string>en</string>
7+
<key>CFBundleExecutable</key>
8+
<string>${EXECUTABLE_NAME}</string>
9+
<key>CFBundleIdentifier</key>
10+
<string>drmohundro.${PRODUCT_NAME:rfc1034identifier}</string>
11+
<key>CFBundleInfoDictionaryVersion</key>
12+
<string>6.0</string>
13+
<key>CFBundleName</key>
14+
<string>${PRODUCT_NAME}</string>
15+
<key>CFBundlePackageType</key>
16+
<string>FMWK</string>
17+
<key>CFBundleShortVersionString</key>
18+
<string>1.0</string>
19+
<key>CFBundleSignature</key>
20+
<string>????</string>
21+
<key>CFBundleVersion</key>
22+
<string>${CURRENT_PROJECT_VERSION}</string>
23+
<key>NSPrincipalClass</key>
24+
<string></string>
25+
</dict>
26+
</plist>

SWXMLHash/SWXMLHash.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
//
2+
// SWXMLHash.h
3+
// SWXMLHash
4+
//
5+
// Created by David Mohundro on 7/8/14.
6+
//
7+
//
8+
9+
#import <UIKit/UIKit.h>
10+
11+
//! Project version number for SWXMLHash.
12+
FOUNDATION_EXPORT double SWXMLHashVersionNumber;
13+
14+
//! Project version string for SWXMLHash.
15+
FOUNDATION_EXPORT const unsigned char SWXMLHashVersionString[];
16+
17+
// In this header, you should import all the public headers of your framework using statements like #import <SWXMLHash/PublicHeader.h>
18+
19+

SWXMLHash/SWXMLHash.swift

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
//
2+
// SWXMLHash.swift
3+
//
4+
// Copyright (c) 2014 David Mohundro
5+
//
6+
// Permission is hereby granted, free of charge, to any person obtaining a copy
7+
// of this software and associated documentation files (the "Software"), to deal
8+
// in the Software without restriction, including without limitation the rights
9+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
// copies of the Software, and to permit persons to whom the Software is
11+
// furnished to do so, subject to the following conditions:
12+
//
13+
// The above copyright notice and this permission notice shall be included in
14+
// all copies or substantial portions of the Software.
15+
//
16+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22+
// THE SOFTWARE.
23+
24+
import Foundation
25+
26+
class SWXMLHash : NSObject, NSXMLParserDelegate {
27+
var parsingElement: String = ""
28+
29+
init() {
30+
currentNode = root
31+
super.init()
32+
}
33+
34+
var lastResults: String = ""
35+
36+
var root = XMLElement(name: "root")
37+
var currentNode: XMLElement
38+
var parentStack = [XMLElement]()
39+
40+
func parse(xml: NSString) -> XMLIndexer {
41+
return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding))
42+
}
43+
44+
func parse(data: NSData) -> XMLIndexer {
45+
// clear any prior runs of parse... expected that this won't be necessary, but you never know
46+
parentStack.removeAll(keepCapacity: false)
47+
root = XMLElement(name: "root")
48+
49+
parentStack.append(root)
50+
51+
let parser = NSXMLParser(data: data)
52+
parser.delegate = self
53+
parser.parse()
54+
55+
return XMLIndexer(root)
56+
}
57+
58+
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName: String!, attributes attributeDict: NSDictionary!) {
59+
60+
self.parsingElement = elementName
61+
62+
currentNode = parentStack[parentStack.count - 1].addElement(elementName, withAttributes: attributeDict)
63+
parentStack.append(currentNode)
64+
65+
lastResults = ""
66+
}
67+
68+
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
69+
lastResults += string
70+
}
71+
72+
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {
73+
if !lastResults.isEmpty {
74+
currentNode.text = lastResults
75+
}
76+
77+
parentStack.removeLast()
78+
}
79+
}

SWXMLHash/XMLElement.swift

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//
2+
// SWXMLElement.swift
3+
//
4+
// Copyright (c) 2014 David Mohundro
5+
//
6+
// Permission is hereby granted, free of charge, to any person obtaining a copy
7+
// of this software and associated documentation files (the "Software"), to deal
8+
// in the Software without restriction, including without limitation the rights
9+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
// copies of the Software, and to permit persons to whom the Software is
11+
// furnished to do so, subject to the following conditions:
12+
//
13+
// The above copyright notice and this permission notice shall be included in
14+
// all copies or substantial portions of the Software.
15+
//
16+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22+
// THE SOFTWARE.
23+
24+
import UIKit
25+
26+
class XMLElement {
27+
var text: String?
28+
let name: String
29+
var elements = [String:[XMLElement]]()
30+
var attributes = [String:String]()
31+
32+
init(name: String) {
33+
self.name = name
34+
}
35+
36+
func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement {
37+
let element = XMLElement(name: name)
38+
39+
if var group = elements[name] {
40+
group.append(element)
41+
elements[name] = group
42+
}
43+
else {
44+
elements[name] = [element]
45+
}
46+
47+
for (keyAny,valueAny) in attributes {
48+
let key = keyAny as String
49+
let value = valueAny as String
50+
element.attributes[key] = value
51+
}
52+
53+
return element
54+
}
55+
}

0 commit comments

Comments
 (0)