-
-
Notifications
You must be signed in to change notification settings - Fork 157
/
Networking-URLSession.swift
83 lines (71 loc) · 2.4 KB
/
Networking-URLSession.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// Networking-URLSession.swift
// Siesta
//
// Created by Paul on 2015/6/26.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
/**
Uses `URLSessionDataTask` for Siesta networking.
This is Siesta’s default networking provider.
*/
public struct URLSessionProvider: NetworkingProvider
{
/// Session which will create `URLSessionDataTask`s.
public let session: URLSession
/// :nodoc:
public init(session: URLSession)
{ self.session = session }
/// :nodoc:
public func startRequest(
_ request: URLRequest,
completion: @escaping RequestNetworkingCompletionCallback)
-> RequestNetworking
{
let task = session.dataTask(with: request)
{ completion($1 as? HTTPURLResponse, $0, $2) }
return URLSessionRequestNetworking(task: task)
}
}
private struct URLSessionRequestNetworking: RequestNetworking, SessionTaskContainer
{
var task: URLSessionTask
fileprivate init(task: URLSessionDataTask)
{
self.task = task
task.resume()
}
func cancel()
{ task.cancel() }
}
extension URLSession: NetworkingProviderConvertible
{
/// You can pass a `URLSession` when creating a `Service`.
public var siestaNetworkingProvider: NetworkingProvider
{ return URLSessionProvider(session: self) }
}
extension URLSessionConfiguration: NetworkingProviderConvertible
{
/// You can pass a `URLSessionConfiguration` when creating a `Service`.
public var siestaNetworkingProvider: NetworkingProvider
{ return URLSession(configuration: self).siestaNetworkingProvider }
}
/// Convenience for `NetworkingProvider` implementations that ultimate rely on a `URLSessionTask`.
public protocol SessionTaskContainer
{
/// Underlying networking task that can report request progress.
var task: URLSessionTask { get }
}
extension SessionTaskContainer
{
/// Extracts transfer metrics using bytes counts from `URLSessionTask`.
public var transferMetrics: RequestTransferMetrics
{
return RequestTransferMetrics(
requestBytesSent: task.countOfBytesSent,
requestBytesTotal: task.countOfBytesExpectedToSend,
responseBytesReceived: task.countOfBytesReceived,
responseBytesTotal: task.countOfBytesExpectedToReceive)
}
}