HTTPRequest

open class HTTPRequest : HTTPRequestProtocol, Equatable, CustomStringConvertible, @unchecked Sendable

HTTP请求基类,支持缓存和重试机制,使用时继承即可

注意事项: 如果vc请求回调句柄中未使用weak self,会产生强引用,则self会在vc关闭且等待请求完成后才会释放 如果vc请求回调句柄中使用了weak self,不会产生强引用,则self会在vc关闭时立即释放,不会等待请求完成

YTKNetwork

  • 请求完成句柄

    Declaration

    Swift

    public typealias Completion = @MainActor @Sendable (HTTPRequest) -> Void
  • 请求构建器,可继承

    继承HTTPRequest并重载Builder示例:

    class AppRequest: HTTPRequest {
        class Builder: HTTPRequest.Builder {
            override func build() -> AppRequest {
                return AppRequest(builder: self)
            }
        }
    }
    

    使用AppRequest.Builder示例:

    let request = AppRequest.Builder()/*...*/.build()
    
    See more

    Declaration

    Swift

    open class Builder

Accessor

  • 自定义请求代理

    Declaration

    Swift

    open weak var delegate: RequestDelegate?
  • tag

    自定义标签,默认0

    Declaration

    Swift

    open var tag: Int
  • 当前请求的上下文,支持UIViewController|UIView

    Declaration

    Swift

    open weak var context: AnyObject?
  • 是否自动显示错误信息,context可不存在

    Declaration

    Swift

    open var autoShowError: Bool
  • 是否自动显示加载信息,context必须存在

    Declaration

    Swift

    open var autoShowLoading: Bool
  • 自定义成功主线程回调句柄

    Declaration

    Swift

    open var successCompletionBlock: Completion?
  • 自定义失败主线程回调句柄

    Declaration

    Swift

    open var failureCompletionBlock: Completion?
  • 自定义取消回调句柄,不一定主线程调用

    Declaration

    Swift

    open var requestCancelledBlock: (@Sendable (HTTPRequest) -> Void)?
  • 自定义请求配件数组

    Declaration

    Swift

    open var requestAccessories: [RequestAccessoryProtocol]?
  • 自定义POST请求HTTP body数据

    Declaration

    Swift

    open var constructingBodyBlock: (@Sendable (RequestMultipartFormData) -> Void)?
  • 断点续传下载路径

    Declaration

    Swift

    open var resumableDownloadPath: String?
  • 断点续传进度句柄

    Declaration

    Swift

    open var downloadProgressBlock: (@Sendable (Progress) -> Void)?
  • 上传进度句柄

    Declaration

    Swift

    open var uploadProgressBlock: (@Sendable (Progress) -> Void)?
  • 请求优先级,默认default

    Declaration

    Swift

    open var requestPriority: RequestPriority
  • 是否是同步串行请求,默认false为异步并发请求

    Declaration

    Swift

    open var isSynchronously: Bool
  • 自定义用户信息

    Declaration

    Swift

    open var requestUserInfo: [AnyHashable : Any]?
  • 是否预加载请求缓存模型(一般仅GET开启),注意开启后当缓存存在时会调用成功句柄一次,默认false

    Declaration

    Swift

    open var preloadCacheModel: Bool { get set }
  • 判断缓存是否存在

    Declaration

    Swift

    open var isResponseCached: Bool { get }
  • 是否是本地缓存数据

    Declaration

    Swift

    open private(set) var isDataFromCache: Bool { get }
  • 当前请求唯一标志符,只读

    Declaration

    Swift

    public let requestIdentifier: String
  • 当前请求适配器,根据插件不同而不同

    Declaration

    Swift

    open var requestAdapter: Any?
  • 当前URLSessionTask,请求开始后才可用

    Declaration

    Swift

    open var requestTask: URLSessionTask?
  • 当前响应Header

    Declaration

    Swift

    open var responseHeaders: [AnyHashable : Any]? { get }
  • 当前响应状态码

    Declaration

    Swift

    open var responseStatusCode: Int { get }
  • 当前响应服务器时间

    Declaration

    Swift

    open var responseServerTime: TimeInterval { get }
  • 请求开始时间

    Declaration

    Swift

    open internal(set) var requestStartTime: TimeInterval { get }
  • 请求总次数

    Declaration

    Swift

    open internal(set) var requestTotalCount: Int { get }
  • 请求总时长

    Declaration

    Swift

    open internal(set) var requestTotalTime: TimeInterval { get }
  • 请求是否已完成,requestTask必须完成且error为nil

    Declaration

    Swift

    open var isFinished: Bool { get }
  • 请求是否已失败,error不为nil,不检查requestTask

    Declaration

    Swift

    open var isFailed: Bool { get }
  • 请求是否已取消,含手动取消和requestTask取消

    Declaration

    Swift

    open var isCancelled: Bool { get }
  • 请求是否已开始,已开始之后再次调用start不会生效

    Declaration

    Swift

    open private(set) var isStarted: Bool { get }
  • 请求是否已暂停,已开始之后才可暂停

    Declaration

    Swift

    open private(set) var isSuspended: Bool { get }
  • 请求是否执行中,requestTask状态为running

    Declaration

    Swift

    open var isExecuting: Bool { get }
  • 当前响应数据

    Declaration

    Swift

    open var responseData: Data? { get set }
  • 当前响应字符串

    Declaration

    Swift

    open var responseString: String? { get set }
  • 当前响应对象

    Declaration

    Swift

    open var responseObject: Any? { get set }
  • 当前响应JSON对象

    Declaration

    Swift

    open var responseJSONObject: Any? { get set }
  • 当前网络错误

    Declaration

    Swift

    open var error: Error? { get set }
  • 自定义请求配置,未设置时使用全局配置

    Declaration

    Swift

    open var config: RequestConfig! { get set }
  • 请求构建器,从构建器初始化时才有值

    Declaration

    Swift

    open private(set) var builder: Builder? { get }
  • 请求上下文控件,可自定义

    Declaration

    Swift

    open var contextAccessory: RequestContextAccessory { get set }

Lifecycle

  • 初始化方法

    Declaration

    Swift

    public init()
  • 指定构建器并初始化

    Declaration

    Swift

    public convenience init(builder: Builder)
  • 请求描述

    Declaration

    Swift

    open var description: String { get }

Override+Request

  • 请求基准URL,默认空,示例:https://www.wuyong.site

    Declaration

    Swift

    open func baseUrl() -> String
  • 请求URL地址,默认空,示例:/v1/user

    Declaration

    Swift

    open func requestUrl() -> String
  • 请求可选CDN地址,默认空

    Declaration

    Swift

    open func cdnUrl() -> String
  • 是否使用CDN

    Declaration

    Swift

    open func useCDN() -> Bool
  • 是否允许蜂窝网络访问,默认true

    Declaration

    Swift

    open func allowsCellularAccess() -> Bool
  • 请求超时,默认60秒

    Declaration

    Swift

    open func requestTimeoutInterval() -> TimeInterval
  • 自定义请求缓存策略,默认nil不处理

    Declaration

    Swift

    open func requestCachePolicy() -> URLRequest.CachePolicy?
  • 请求方式,默认GET

    Declaration

    Swift

    open func requestMethod() -> RequestMethod
  • 请求附加参数,建议[String: Any]?,默认nil

    Declaration

    Swift

    open func requestArgument() -> Any?
  • 请求序列化方式,默认HTTP

    Declaration

    Swift

    open func requestSerializerType() -> RequestSerializerType
  • 响应序列化方式,默认JSON

    Declaration

    Swift

    open func responseSerializerType() -> ResponseSerializerType
  • HTTP请求授权Header数组,示例:[“UserName”, “Password”]

    Declaration

    Swift

    open func requestAuthorizationHeaders() -> [String]?
  • 自定义请求Header字典

    Declaration

    Swift

    open func requestHeaders() -> [String : String]?
  • 请求发送前URLRequest过滤方法,默认不处理

    Declaration

    Swift

    open func urlRequestFilter(_ urlRequest: inout URLRequest)
  • 构建自定义URLRequest

    Declaration

    Swift

    open func customUrlRequest() -> URLRequest?

Override+Response

  • JSON验证器,默认支持AnyValidator

    Declaration

    Swift

    open func jsonValidator() -> Any?
  • 状态码验证器

    Declaration

    Swift

    open func statusCodeValidator() -> Bool
  • 调试请求Mock验证器,默认判断404

    Declaration

    Swift

    open func responseMockValidator() -> Bool
  • 调试请求Mock处理器,请求失败时且回调前在后台线程调用

    Declaration

    Swift

    open func responseMockProcessor() -> Bool
  • 请求回调前Response过滤方法,默认成功不抛异常

    Declaration

    Swift

    open func responseFilter() throws
  • 是否后台预加载响应模型,默认false,仅ResponseModelRequest生效

    Declaration

    Swift

    open func preloadResponseModel() -> Bool
  • 请求完成预处理器,后台线程调用。默认写入请求缓存、预加载响应模型

    Declaration

    Swift

    open func requestCompletePreprocessor()
  • 请求完成过滤器,主线程调用,默认不处理

    Declaration

    Swift

    @MainActor
    open func requestCompleteFilter()
  • 请求失败预处理器,后台线程调用,默认不处理

    Declaration

    Swift

    open func requestFailedPreprocessor()
  • 请求失败过滤器,主线程调用,默认不处理

    Declaration

    Swift

    @MainActor
    open func requestFailedFilter()

Override+Retry

  • 请求重试次数,默认0

    Declaration

    Swift

    open func requestRetryCount() -> Int
  • 请求重试间隔,默认0

    Declaration

    Swift

    open func requestRetryInterval() -> TimeInterval
  • 请求重试超时时间,默认0

    Declaration

    Swift

    open func requestRetryTimeout() -> TimeInterval
  • 请求重试验证方法,默认检查状态码和错误

    Declaration

    Swift

    open func requestRetryValidator(_ response: HTTPURLResponse, responseObject: Any?, error: Error?) -> Bool
  • 请求重试处理方法,回调处理状态,默认调用completionHandler(true)

    Declaration

    Swift

    open func requestRetryProcessor(_ response: HTTPURLResponse, responseObject: Any?, error: Error?, completionHandler: @escaping @Sendable (Bool) -> Void)

Override+Cache

  • 缓存有效期,默认-1不缓存

    Declaration

    Swift

    open func cacheTimeInSeconds() -> Int
  • 缓存版本号,默认0

    Declaration

    Swift

    open func cacheVersion() -> Int
  • 缓存敏感数据,变化时会更新缓存

    Declaration

    Swift

    open func cacheSensitiveData() -> Any?
  • 缓存文件名过滤器,参数为请求参数,默认返回argument

    Declaration

    Swift

    open func cacheArgumentFilter(_ argument: Any?) -> Any?
  • 是否异步写入缓存,默认true

    Declaration

    Swift

    open func writeCacheAsynchronously() -> Bool

Action

  • 当前请求的上下文,支持UIViewController|UIView

    Declaration

    Swift

    @discardableResult
    open func context(_ context: AnyObject?) -> Self
  • 开始请求,已开始后重复调用无效

    Declaration

    Swift

    @discardableResult
    open func start() -> Self
  • 暂停请求,已开始后调用才会生效

    Declaration

    Swift

    @discardableResult
    open func suspend() -> Self
  • 继续请求,未开始或暂停后可调用

    Declaration

    Swift

    @discardableResult
    open func resume() -> Self
  • 取消请求

    Declaration

    Swift

    open func cancel()
  • 断点续传进度句柄

    Declaration

    Swift

    @discardableResult
    open func downloadProgressBlock(_ block: (@Sendable (Progress) -> Void)?) -> Self
  • 上传进度句柄

    Declaration

    Swift

    @discardableResult
    open func uploadProgressBlock(_ block: (@Sendable (Progress) -> Void)?) -> Self
  • 是否自动显示加载信息,context必须存在

    Declaration

    Swift

    @discardableResult
    open func autoShowLoading(_ autoShowLoading: Bool) -> Self
  • 是否自动显示错误信息,context可不存在

    Declaration

    Swift

    @discardableResult
    open func autoShowError(_ autoShowError: Bool) -> Self
  • 显示加载条,默认显示加载插件,context必须存在

    Declaration

    Swift

    open func showLoading()
  • 隐藏加载条,默认隐藏加载插件,context必须存在

    Declaration

    Swift

    open func hideLoading()
  • 显示网络错误,默认显示Toast提示,context可不存在

    Declaration

    Swift

    open func showError()
  • 清理完成句柄

    Declaration

    Swift

    open func clearCompletionBlock()
  • 添加请求配件

    Declaration

    Swift

    @discardableResult
    open func addAccessory(_ accessory: RequestAccessoryProtocol) -> Self

Response

  • 快捷设置响应失败句柄

    Declaration

    Swift

    @discardableResult
    open func responseError(_ block: (@MainActor @Sendable (Error) -> Void)?) -> Self
  • 设置是否预加载响应模型,仅ResponseModelRequest生效

    Declaration

    Swift

    @discardableResult
    open func preloadResponseModel(_ preload: Bool) -> Self
  • 快捷设置模型响应成功句柄,解析成功时自动缓存,支持后台预加载

    Declaration

    Swift

    @discardableResult
    open func responseModel<T>(of type: T.Type, designatedPath: String? = nil, success: (@MainActor @Sendable (T?) -> Void)?) -> Self where T : AnyModel
  • 快捷设置安全模型响应成功句柄,解析成功时自动缓存,支持后台预加载

    Declaration

    Swift

    @discardableResult
    open func safeResponseModel<T>(of type: T.Type, designatedPath: String? = nil, success: (@MainActor @Sendable (T) -> Void)?) -> Self where T : AnyModel

Cache

  • 是否预加载请求缓存模型(一般仅GET开启),注意开启后当缓存存在时会调用成功句柄一次

    Declaration

    Swift

    @discardableResult
    open func preloadCacheModel(_ preloadCacheModel: Bool) -> Self
  • 解析指定缓存响应模型句柄,必须在start之前调用生效

    Declaration

    Swift

    @discardableResult
    open func responseCacheModel<T>(of type: T.Type, designatedPath: String? = nil, success: (@MainActor @Sendable (T?) -> Void)?) -> Self where T : AnyModel
  • 解析指定缓存安全响应模型句柄,必须在start之前调用生效

    Declaration

    Swift

    @discardableResult
    open func responseSafeCacheModel<T>(of type: T.Type, designatedPath: String? = nil, success: (@MainActor @Sendable (T) -> Void)?) -> Self where T : AnyModel
  • 加载本地缓存,返回是否成功

    Declaration

    Swift

    open func loadCache() throws
  • 保存指定数据到缓存文件

    Declaration

    Swift

    @discardableResult
    open func saveCache(_ data: Data?) -> Bool
  • 缓存唯一Id,子类可重写

    Declaration

    Swift

    open func cacheIdentifier() -> String

Equatable

  • Declaration

    Swift

    public static func == (lhs: HTTPRequest, rhs: HTTPRequest) -> Bool