2019-01-05 17:37:34 +00:00
|
|
|
//
|
|
|
|
// NetworkManager.swift
|
|
|
|
// MasKit
|
|
|
|
//
|
|
|
|
// Created by Ben Chatelain on 1/5/19.
|
|
|
|
// Copyright © 2019 mas-cli. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
2019-01-30 06:15:24 +00:00
|
|
|
/// Network abstraction
|
2019-01-06 19:26:08 +00:00
|
|
|
public class NetworkManager {
|
2019-01-06 02:59:12 +00:00
|
|
|
enum NetworkError: Error {
|
|
|
|
case timeout
|
|
|
|
}
|
|
|
|
|
2019-01-05 17:37:34 +00:00
|
|
|
private let session: NetworkSession
|
|
|
|
|
2019-01-06 02:59:12 +00:00
|
|
|
/// Designated initializer
|
|
|
|
///
|
2019-01-06 19:26:08 +00:00
|
|
|
/// - Parameter session: A networking session.
|
|
|
|
public init(session: NetworkSession = URLSession.shared) {
|
2019-01-05 17:37:34 +00:00
|
|
|
self.session = session
|
|
|
|
}
|
2019-01-06 02:59:12 +00:00
|
|
|
|
|
|
|
/// Loads data asynchronously.
|
|
|
|
///
|
|
|
|
/// - Parameters:
|
|
|
|
/// - url: URL to load data from.
|
|
|
|
/// - completionHandler: Closure where result is delivered.
|
2019-01-05 17:37:34 +00:00
|
|
|
func loadData(from url: URL, completionHandler: @escaping (NetworkResult) -> Void) {
|
|
|
|
session.loadData(from: url) { (data: Data?, error: Error?) in
|
2019-01-06 19:26:08 +00:00
|
|
|
let result: NetworkResult = data != nil
|
|
|
|
? .success(data!)
|
|
|
|
: .failure(error!)
|
2019-01-05 17:37:34 +00:00
|
|
|
completionHandler(result)
|
|
|
|
}
|
|
|
|
}
|
2019-01-06 02:59:12 +00:00
|
|
|
|
|
|
|
/// 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
|
|
|
|
}
|
2019-01-05 17:37:34 +00:00
|
|
|
}
|