美文网首页
Alamofire(3)SessionManager

Alamofire(3)SessionManager

作者: 忆痕无殇 | 来源:发表于2019-08-21 11:38 被阅读0次

    SessionManager

    先来一张思维导图


    SenssionManager.jpg

    1:'default'

    /// A default instance ofSessionManager, used by top-level Alamofire request methods, and suitable for use
    /// directly for any ad hoc requests.

     public static let `default`: SessionManager = {
            let configuration = URLSessionConfiguration.default
            configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
    
            return SessionManager(configuration: configuration)
        }()
    

    'default'是个单利模式,默认设置编码方式、语言、和配置信息等。会在这里标入一些自己的特殊标记进行安全的校验,非法信息的拦截。

    2:init

      private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) {
            session.serverTrustPolicyManager = serverTrustPolicyManager
    
            delegate.sessionManager = self
    
            delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
                guard let strongSelf = self else { return }
                DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() }
            }
        }
    

    DispatchQueue.main.async when finished返回主线程操作。

    If you need to handle your own events before the handler is called, then you need to override the
    /// SessionDelegatesessionDidFinishEventsForBackgroundURLSessionand manually call the handler when finished.

    3: download

     open func download(
            _ url: URLConvertible,
            method: HTTPMethod = .get,
            parameters: Parameters? = nil,
            encoding: ParameterEncoding = URLEncoding.default,
            headers: HTTPHeaders? = nil,
            to destination: DownloadRequest.DownloadFileDestination? = nil)
            -> DownloadRequest
        {
            do {
                let urlRequest = try URLRequest(url: url, method: method, headers: headers)
                let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
                return download(encodedURLRequest, to: destination)
            } catch {
                return download(nil, to: destination, failedWith: error)
            }
        }
    
    

    下载请求默认get方法。parameters参数需要转成json格式与后台进行交互。否则会有编码格式问题。

    4:encode
     public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
            var urlRequest = try urlRequest.asURLRequest()
    
            guard let parameters = parameters else { return urlRequest }
    
            if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
                guard let url = urlRequest.url else {
                    throw AFError.parameterEncodingFailed(reason: .missingURL)
                }
    
                if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
                    let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
                    urlComponents.percentEncodedQuery = percentEncodedQuery
                    urlRequest.url = urlComponents.url
                }
            } else {
                if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
                    urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
                }
    
                urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
            }
    
            return urlRequest
        }
    

    GET方法会在url连接中拼接"&"符号。POST方法会在body里添加数据。
    let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
    5:upload

      open func upload(
            _ fileURL: URL,
            to url: URLConvertible,
            method: HTTPMethod = .post,
            headers: HTTPHeaders? = nil)
            -> UploadRequest
        {
            do {
                let urlRequest = try URLRequest(url: url, method: method, headers: headers)
                return upload(fileURL, with: urlRequest)
            } catch {
                return upload(nil, failedWith: error)
            }
        }
    

    相关文章

      网友评论

          本文标题:Alamofire(3)SessionManager

          本文链接:https://www.haomeiwen.com/subject/fqgvsctx.html