-
Notifications
You must be signed in to change notification settings - Fork 276
/
NetworkManager.swift
60 lines (51 loc) · 1.59 KB
/
NetworkManager.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
//
// NetworkManager.swift
// MasKit
//
// Created by Ben Chatelain on 1/5/19.
// Copyright © 2019 mas-cli. All rights reserved.
//
import Foundation
/// Network abstraction
public class NetworkManager {
enum NetworkError: Error {
case timeout
}
private let session: NetworkSession
/// Designated initializer
///
/// - Parameter session: A networking session.
public init(session: NetworkSession = URLSession.shared) {
self.session = session
}
/// Loads data asynchronously.
///
/// - Parameters:
/// - url: URL to load data from.
/// - completionHandler: Closure where result is delivered.
func loadData(from url: URL, completionHandler: @escaping (NetworkResult) -> Void) {
session.loadData(from: url) { (data: Data?, error: Error?) in
let result: NetworkResult = data != nil
? .success(data!)
: .failure(error!)
completionHandler(result)
}
}
/// Loads data synchronously.
///
/// - Parameter url: URL to load data from.
/// - Returns: Network result containing either Data or an Error.
func loadDataSync(from url: URL) -> NetworkResult {
var syncResult: NetworkResult?
let semaphore = DispatchSemaphore(value: 0)
loadData(from: url) { asyncResult in
syncResult = asyncResult
semaphore.signal()
}
_ = semaphore.wait(timeout: .distantFuture)
guard let result = syncResult else {
return .failure(NetworkError.timeout)
}
return result
}
}