mas/MasKit/Network/NetworkManager.swift

61 lines
1.6 KiB
Swift
Raw Normal View History

//
// 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
}
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) {
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.
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!)
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
}
}