-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParseSearchResultsOperation.swift
More file actions
79 lines (64 loc) · 2.29 KB
/
ParseSearchResultsOperation.swift
File metadata and controls
79 lines (64 loc) · 2.29 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
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Contains the logic to parse a JSON file of https feed and return result
*/
import CoreLocation
import Foundation
import UIKit
/// A struct to represent a parsed search result.
struct ParsedSearchResult {
// MARK: Properties.
// MARK: Initialization
let location: CLLocation?
let placesOfInterest: [[String: AnyObject]]?
init?(coords: [String: AnyObject], data: [
[String: AnyObject]]) {
self.placesOfInterest = data
guard let latitude = (coords["lat"] as? NSString)?.doubleValue,
let longitude = (coords["lng"] as? NSString)?.doubleValue else {
return nil
}
location = CLLocation.init(latitude: latitude, longitude: longitude)
}
}
class ParseSearchResultsOperation: Operation {
let cacheFile: NSURL
let completionHandler: (ParsedSearchResult) -> Void
init(cacheFile: NSURL, completionHandler: (ParsedSearchResult) -> Void) {
self.cacheFile = cacheFile
self.completionHandler = completionHandler
super.init()
name = "Parse Search Results"
}
override func execute() {
guard let stream = NSInputStream(URL: cacheFile) else {
finish()
return
}
stream.open()
defer {
stream.close()
}
do {
let json = try NSJSONSerialization.JSONObjectWithStream(stream, options: []) as? [String: AnyObject]
guard let coords = json?["coords"] as? [String: AnyObject],
let data = json?["data"] as? [[String: AnyObject]] else {
finish()
return
}
parseJSON(coords, data: data)
}
catch let jsonError as NSError {
finishWithError(jsonError)
}
}
private func parseJSON(coords: [String: AnyObject], data: [[String: AnyObject]]) {
guard let parsedCoords = ParsedSearchResult(coords: coords, data: data) else {
self.finishWithError(NSError(domain: "can't create file", code: -1, userInfo: nil))
return
}
self.completionHandler(parsedCoords)
}
}