-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJSONDownloader.swift
More file actions
69 lines (61 loc) · 2 KB
/
Copy pathJSONDownloader.swift
File metadata and controls
69 lines (61 loc) · 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
//
// JSONDownloader.swift
// JSONTutorial
//
// Created by Kapil Amagain on 5/11/17.
// Copyright © 2017 James Rochabrun. All rights reserved.
//
import Foundation
struct JSONDownloader {
//1)
let session: URLSession
init(configuration: URLSessionConfiguration) {
self.session = URLSession(configuration: configuration)
}
init() {
self.init(configuration: .default)
}
typealias JSON = [String: AnyObject]
typealias JSONTaskCompletionHandler = (Result<JSON>) -> ()
//4)
func jsonTask(with request: URLRequest, completionHandler completion: @escaping JSONTaskCompletionHandler) -> URLSessionDataTask {
let task = session.dataTask(with: request) { (data, response, error) in
guard let httpResponse = response as? HTTPURLResponse else {
completion(.Error(.requestFailed))
return
}
if httpResponse.statusCode == 200 {
if let data = data {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] {
DispatchQueue.main.async {
completion(.Success(json))
}
}
}
catch {
completion(.Error(.jsonConversionFailure))
}
} else {
completion(.Error(.invalidData))
}
} else {
completion(.Error(.responseUnsuccessful))
print("\(error)")
}
}
return task
}
}
enum Result<T> {
case Success(T)
case Error(ItunesAPIError)
}
enum ItunesAPIError: Error {
case requestFailed
case jsonConversionFailure
case invalidData
case responseUnsuccessful
case invalidURL
case jsonParsingFailure
}