Network.swift 5.35 KB
Newer Older
曹云霄's avatar
曹云霄 committed
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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
//
//  Network.swift
//  GitHub
//
//  Created by 曹云霄 on 2017/12/5.
//  Copyright © 2017年 曹云霄. All rights reserved.
//
import Moya
import SwiftyJSON
import SVProgressHUD


struct Network {
    
    // 请求头
    static let publicParamEndpointPlugin = { (target: Service) -> Endpoint<Service> in
        let url = target.baseURL.absoluteString + target.path
        let endpoint = Endpoint<Service>(url: url, sampleResponseClosure: { .networkResponse(200, target.sampleData) }, method: target.method, task: target.task, httpHeaderFields: target.headers)
        var enterprise = ""
//        if let userModel = AppManager.shareInstance.userModel {
//            enterprise = userModel.enterpriseUuid;
//        }
        return endpoint.adding(newHTTPHeaderFields: ["enterprise" : enterprise,"Content-Type" : "application/json;charset=utf-8"])
    }
    
    // 设置超时时间
    static let requestClosurePlugin = {(endpoint: Endpoint<Service>, closure: MoyaProvider<Service>.RequestResultClosure) -> Void in
        do {
           var urlRequest = try endpoint.urlRequest()
            urlRequest.timeoutInterval = 30
            closure(.success(urlRequest))
        } catch  {
            closure(.failure(MoyaError.requestMapping(endpoint.url)))
        }
    }

    // 监听请求状态
    static let networkActivityPlugin = NetworkActivityPlugin { (type,target)  in
        switch type {
        case .began:
//            ShowLoadingView()
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        case .ended:
//            HideLoadingView()
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        }
    }
    
    // 日志
    static let logPlugin =  NetworkLoggerPlugin(verbose: true, cURL: true, output: { (_ separator: String,_ terminator: String,_ items: Any...) in
        for item in items{
            print("---\((item as! String).replacingOccurrences(of: "\\", with: ""))")
        }
    }, requestDataFormatter: nil, responseDataFormatter: nil)
    
    // 公告请求对象
    static let provider = MoyaProvider<Service>(endpointClosure: publicParamEndpointPlugin,requestClosure: requestClosurePlugin,plugins: [networkActivityPlugin,logPlugin])

    // MARK: -取消所有请求
    static func cancelAllRequest() {
        provider.manager.session.invalidateAndCancel()
    }
    
    
    
    /// 文件上传
    ///
    /// - Parameters:
    ///   - target:   请求方法
    ///   - progress: 上传进度
    ///   - success:  成功回调
    ///   - failure:  失败回调
    static func upload(target: Service,progress: @escaping(Double) -> Void ,success: @escaping (JSON) -> Void, failure: @escaping (MoyaError) -> Void) {
        provider.request(target, progress: { (pro) in
            progress(pro.progress)
        }) { (result) in
            switch result {
            /// 请求成功后先通过json解析数据,如果解析失败使用jsonString重试一次
            case let .success(response):
                do {
                    guard response.statusCode == 200 else {
                        failure(MoyaError.statusCode(response))
                        return
                    }
                    let json = try response.mapJSON()
                    success(JSON(json))
                } catch {
                    switch (error) {
                    case MoyaError.jsonMapping(response):
                        do {
                            let jsonString = try response.mapString()
                            success(JSON(jsonString))
                        }catch {
                            failure(error as! MoyaError)
                        }
                    default:
                        failure(error as! MoyaError)
                        break
                    }
                }
                break
            case let .failure(error):
                failure(error)
                break
            }
        }
    }

    /// 公共请求方法
    ///
    /// - Parameters:
    ///   - target:  请求方法
    ///   - success: 请求成功
    ///   - error:   请求失败
    static func request(target: Service, success: @escaping (JSON) -> Void, failure: @escaping (MoyaError) -> Void) {
        provider.request(target) { result in
            switch result {
            /// 请求成功后先通过json解析数据,如果解析失败使用jsonString重试一次
            case let .success(response):
                do {
                    guard response.statusCode == 200 else {
                        failure(MoyaError.statusCode(response))
                        return
                    }
                    let json = try response.mapJSON()
                    success(JSON(json))
                } catch {
                    switch (error) {
                    case MoyaError.jsonMapping(response):
                        do {
                            let jsonString = try response.mapString()
                            success(JSON(jsonString))
                        }catch {
                            failure(error as! MoyaError)
                        }
                    default:
                        failure(error as! MoyaError)
                        break
                    }
                }
                break
            case let .failure(error):
                failure(error)
                break
            }
        }
    }
}