[작성중] Alamofire Request 정리

Posted by Neph's Blog on September 26, 2022
  • State
    • Initial State
    • Mutable State
  • Progress
  • Redirect Handling
  • Cached Response Handling
  • URLCredential
  • Validator
  • URLRequests
  • HTTPURLResponse
  • Tasks
  • Metrics
  • Retry Count
  • Error

State

State

State는 다음과 같이 구성되어 있습니다.

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
public enum State {
    /// Initial state of the `Request`.
    case initialized
    /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
    /// them in this state.
    case resumed
    /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
    /// them in this state.
    case suspended
    /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
    /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
    /// to any other state.
    case cancelled
    /// `State` set when all response serialization completion closures have been cleared on the `Request` and
    /// enqueued on their respective queues.
    case finished

    /// Determines whether `self` can be transitioned to the provided `State`.
    func canTransitionTo(_ state: State) -> Bool {
        switch (self, state) {
        case (.initialized, _):
            return true
        case (_, .initialized), (.cancelled, _), (.finished, _):
            return false
        case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
            return true
        case (.suspended, .suspended), (.resumed, .resumed):
            return false
        case (_, .finished):
            return true
        }
    }
  • initialized (초기 상태)
  • resumed (task가 resume되었을 때의 상태)
  • suspended (중지되었을 때의 상태)
  • cancelled (취소되었을 때의 상태)
  • finished (완료되었을 때의 상태)

총 5가지 상태가 존재합니다. 상태전이 가능의 여부는 canTransitionTo(_: State) 로 체크할 수 있습니다.

Initial State

State는 시점에 따라 크게 Initial StateMutable State로 나뉩니다.

그중 Initial State때 세팅되는 프로퍼티들은 다음과 같습니다.

1
2
3
4
5
6
7
8
9
10
11
12
/// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
public let id: UUID
/// The serial queue for all internal async actions.
public let underlyingQueue: DispatchQueue
/// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
public let serializationQueue: DispatchQueue
/// `EventMonitor` used for event callbacks.
public let eventMonitor: EventMonitor?
/// The `Request`'s interceptor.
public let interceptor: RequestInterceptor?
/// The `Request`'s delegate.
public private(set) weak var delegate: RequestDelegate?

Request를 구분짓는 id값, 지정가능한 DispatchQueue, eventMonitor, interceptor, delegate 등이 있습니다.

위의 값들은 public이기 때문에 라이브러리를 사용하는 경우에도 꺼내 쓸 수 있습니다.

반면 Mutable State의 값들은 internal이라 꺼내 쓸 수 없으니 다루지 않도록 하겠습니다.

현재 상태 확인법

1
2
3
4
5
6
7
8
9
10
11
12
/// `State` of the `Request`.
public var state: State { $mutableState.state }
/// Returns whether `state` is `.initialized`.
public var isInitialized: Bool { state == .initialized }
/// Returns whether `state is `.resumed`.
public var isResumed: Bool { state == .resumed }
/// Returns whether `state` is `.suspended`.
public var isSuspended: Bool { state == .suspended }
/// Returns whether `state` is `.cancelled`.
public var isCancelled: Bool { state == .cancelled }
/// Returns whether `state` is `.finished`.
public var isFinished: Bool { state == .finished }

state라는 변수와 함께 각종 상황이 진행되었는지를 체크할 수 있는 변수가 주어지므로

이를 통해 현재 Request의 상태를 확인할 수 있습니다.

기타

Requests

1
2
3
4
5
6
7
8
9
10
11
12
/// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
public var requests: [URLRequest] { $mutableState.requests }
/// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
public var firstRequest: URLRequest? { requests.first }
/// Last `URLRequest` created on behalf of the `Request`.
public var lastRequest: URLRequest? { requests.last }
/// Current `URLRequest` created on behalf of the `Request`.
public var request: URLRequest? { lastRequest }

/// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
/// `requests` due to `URLSession` manipulation.
public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap(\.currentRequest) } }

request를 꺼내 볼 수 있는 연산 프로퍼티들입니다.

이미 진행된 requests만 따로 볼 수 있는 perfromedRequests를 지원합니다.

HTTPURLResponse

1
2
3
/// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
/// last `URLSessionTask`.
public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }