Moya

简介

Moya是一个网络抽象层的老三正值斯威夫特库,它至关首要集成了Alamofire,并举办了一个抽象层的接口类为MoyaProvider,利用这provider就足以展开局部request了。
Network abstraction layer written in Swift.

Moya对比

用法

官方使用文档地址:https://moya.github.io

对比

  • 昔日大家举办网络要,一般是为此系统的URLSession,然后新建一个Task举办呼吁;

  • 依旧用Alamofire间接调用其基于URLSession封装的哀求方法request(_:),但如果每个请求都应用同一的一致堆放代码,举办response处理代码的话,就生出接触冗余了;

  • 为此Moya做的事情就是拿要的切实落实封装到内,然后定义一个商TargetType,基于这几个协议而得指定每个请求的baseURL、path、method、parameters、parametersEncoding等,方便集中管理每个系列模块中之所以到的数量接口;

集成

  • 假定手动集成Moya,你得用CocoaPods也堪用Carthage,也支撑斯威夫特(Swift)(Swift)Package
    Manager,并且有Rx和ReactNative的本,具体用法见https://moya.github.io

  • 村办推举用Carthage,对斯威夫特(Swift)(Swift)匡助得还好;

Target
  • 要牵挂利用Moya,就得叫所用之API接口听从Moya.TargetType协议,然后创制一个Moya.Provider<Moya.TargetType>对象就可针对你的Target发起网络要了。

  • 下坐豆瓣电台也例简单演示下实际用法;

  1. 概念一个enum为DoubanAPI,并定义网络接口:

enum DoubanAPI {
    case channels
    case playList(channel: String)
}
  1. 为DoubanAPI遵循TargetType协议,并实现相应的习性:

var task: Task{
    return .request
}
  • 瞩目这里的Task一共有3种植,可以针对不同的api接口用switch self指定各自的task类型:

public enum Task {
// 普通网络要
case request
// 文件上传
case upload(Moya.UploadType)
// 文件下充斥
case download(Moya.DownloadType)
}

  • 随着实现协议中之任何性能

var baseURL: URL{
    switch self {
    case .channels:
        return URL(string: "https://www.douban.com")!
    case .playList(_):
        return URL(string: "https://douban.fm")!
    }
}

var path: String{
    switch self {
    case .channels:
        return "/j/app/radio/channels"
    case .playList(_):
        return "/j/mine/playlist"
    }
}

var method: Moya.Method{
    return .get
}
// 是否需要Alamofire校验url
var validate: Bool{
    return false
}
// 测试数据,单元测试时用
var sampleData: Data{
    return "{}".data(using: .utf8)!
}

var parameters: [String : Any]?{
    switch self {
    case .playList(let channel):
        return ["channel": channel, 
                "type": "n", 
                "from": "mainsite"]
    default:
        return nil
    }
}

var parameterEncoding: ParameterEncoding{
    return URLEncoding.default
}
Request
let provider = MoyaProvider<DoubanAPI>()
provider.request(target) {
    switch $0{
    case .success(let response):
        print("[Network Request] : \(response.request?.url?.absoluteString ?? "")")

        // 数据解析成JSON
        guard  let json: [String: Any] = response.json() else{
            failure(.jsonMapping(response))
            return
        }

        // 网络返回的错误提示信息:如用户名不存在等;
        guard let status = json["status"] as? Bool, status else{
            error(json["message"] as? String ?? "未知错误")
            return
        }

        // 网络请求成功
        success(json)
    case .failure(let error):
        // 服务器错误:如网络连接失败,请求超时等;
        failure(error)
    }
}
  • 顾下边的response.json()方法是对Moya.Response的恢弘,用来将Data解析成JSON;

extension Moya.Response{
    func json<T>() -> T?{
        guard 
            let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? T else {
                return nil
        }
        return json
    }
}
  • 只是假设每个接口,都设新建一个MoyaProvider,再发起呼吁,未免有硌最过累,所以可以考虑重新包一重叠为Network;

import UIKit
import Moya

struct Network {
// 注意这里只是针对特定DoubanAPI的Provider这样有局限性
    static let defaultProvider = MoyaProvider<DoubanAPI>()

    static func request(_ target: DoubanAPI
                        success: @escaping (([String: Any]) -> Void), // 成功
                        error: @escaping ((String) -> Void),  // 服务器错误提示
                        failure: @escaping ((MoyaError) -> Void)){ // 网络请求失败
        defaultProvider.request(target) { /*进行一些处理,这里就和上边的一样了*/ 
                }
    }
}
  • 使用

Network.request(.channels, viewController: self, success: { 
            guard 
                let array = $0["channels"] as? [[String: Any]] else{
                    print("数据解析失败")
                    return
            }
            self.data = array
            self.tableView.reloadData()
        }, error: { 
            self.showErrorAlert(title: "数据请求失败", message: $0)
        }) { 
            self.showErrorAlert(title: "网络错误", message: $0.localizedDescription)
        }
  • 张冠李戴指示

extension UIViewController{
    func showErrorAlert(title: String?, message: String){
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(.init(title: "OK", style: .cancel, handler: nil))

        present(alert, animated: true, completion: nil)
    }
}
  • 这样一来,就好于另外地点简洁使用provider的request了;

  • 但是此也生一个题目,固然封装出来了,但上的Network明显不可能适配更活的央求情状,比如自己还有一个模块于MovieAPI,那就未可以由此Network.request了,因为以上只是是对准DoubanAPI的Target进行的求;

  • 吓当Moya提供了一个深受MultiTarget的enum,当然它们是遵照TargetType的,只是内把一个单独的target给包裹起来,达到适配的目标;

  • 对Network的改建如下:

// 只是简单讲DoubanAPI改为通配的MultiTarget
static let defaultProvider = MoyaProvider<MultiTarget>()
  • 接纳(只需要依据target新建一个MultiTarget)public init(_ target: TargetType)

Network.request(MultiTarget(DoubanAPI.channels))...
Network.request(MultiTarget(MovieAPI.list))...
Download
  • 通向DoubanAPI扩张一个下载mp3的接口:case downloadMP4(String)
  • 指定下载的baseURL和path、task:

var task: Task{
        switch self {
        case .downloadMP4(_):
// 下载文件需要指定下载目录
            return .download(.request(DefaultDownloadDestination))
        default:
            return .request
        }
    }
var baseURL: URL{
        switch self {
        case .downloadMP4(let url):
            return URL(string: url)!
        }
    }

    var path: String{
        switch self {
        default:
            return ""
        }
    }
  • 默认的下载目录也Documents

let DefaultDownloadDestination: DownloadDestination = { temporaryURL, response in
    let directoryURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

    if !directoryURLs.isEmpty {
        return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [.removePreviousFile])
    }

    return (temporaryURL, [])
}
  • 以Network中查封装统一的下载情势:

struct Network {
    typealias Success = (([String: Any]) -> Void)
    typealias Error = ((String) -> Void)
    typealias Failure = ((MoyaError) -> Void)
    typealias Progress = ((Double, Bool) -> Void)
}
static func download(_ target: MultiTarget, 
                         progress: @escaping Progress, 
                         failure: @escaping Failure){
        defaultProvider.request(target, queue: DispatchQueue.main, progress: { 
            progress($0.progress, $0.completed)
        }) { 
            switch $0{
                case .success:
                    progress(1, true)
                case .failure(let error):
                    failure(error)
            }
        }
    }
  • 使用

@IBAction func downloadMP4(_ sender: Any){
        self.downloadBtn.isEnabled = false
        Network.download(MultiTarget(API.downloadMP4(self.url ?? "")), progress: { (progress, isCompleted) in

            let title = isCompleted ? "已下载" : "\(progress * 100) %"
            self.downloadBtn.titleLabel?.text = title
            self.downloadBtn.setTitle(title, for: .normal)

        }) { 
            self.showErrorAlert(title: "下载失败", message: $0.errorDescription ?? "未知错误")
            self.downloadBtn.isEnabled = true
        }
    }
Upload
  • 追加API网络接口task:

var task: Task{
        switch self {
        case let .uploadGif(data):
            return .upload(.multipart([
                .init(provider: .data(data), name: "file")
            ]))
        }
    }
  • 指定baseURL、path和parameters、method等:

var baseURL: URL{
        switch self {
        case .uploadGif:
            return URL(string: "https://upload.giphy.com")!
        }
    }

    var path: String{
        switch self {
        case .uploadGif:
            return "/v1/gifs"
        }
    }

    var method: Moya.Method{
        switch self {
        case .uploadGif:
            return .post
              }
    }
  • 在Network中增加upload方法:

static func upload(_ target: MultiTarget, 
                         progress: @escaping Progress, 
                         failure: @escaping Failure, 
                         error: @escaping Error){
        defaultProvider.request(target, queue: DispatchQueue.main, progress: { 
                if let response = $0.response{ 
//服务器有可能会报错误,此时progress却为1
                response.statusCode == 200 
                    ? progress($0.progress, $0.completed)
                    : failure(MoyaError.statusCode(response))
            }
        }) { 
            switch $0{
            case let .success(response):
                if let json: JSONDictionary = response.json(),
                    let meta = json["meta"] as? JSONDictionary,
                    let status = meta["status"] as? Int, 
                    let msg = meta["msg"] as? String{
                    status == 200 && msg == "OK"
                        ? progress(1, true) 
                        : error(msg)
                }
                else{
                    error("未知原因")
                }
            case .failure(let error):
                failure(error)
            }
        }
    }
  • 使用:

@IBAction func uploadGif(_ sender: Any?) {
        uploadBtn.isUserInteractionEnabled = false
    Network.upload(MultiTarget.init(API.uploadGif(animatedBirdGifData())), progress: { 
            let title = ($0 >= 1 && $1) ? "上传完成" : "\(Int($0 * 100)) %"
            self.uploadBtn.titleLabel?.text = title
            self.uploadBtn.setTitle(title, for: .normal)
        }, failure: { 
            handleUploadError($0.localizedDescription)
        }){
            handleUploadError($0)
        }

        func handleUploadError(_ error: String){
            self.showErrorAlert(title: "上传Gif失败", message: error)
            self.uploadBtn.isUserInteractionEnabled = true
            self.uploadBtn.setTitle("重新上传", for: .normal)
        }
    }
Plugin
  • 以Moya中暴发一个磋商叫PluginType,功能是于倡导呼吁和呼吁了时回调,举办一些新闻处理同唤醒,如HUD提醒,打印请求信息至极;

  • Moya默认提供了2独plugin:NetworkLoggerPluginNetworkActivityPlugin,牵在用于请求音信之log打印,后者用于请求的监听,有2种状态beganended

  • 于是法(注意是匹配请求的发起者provider使用的):

static let defaultProvider = MoyaProvider<MultiTarget>(plugins:[
// verbose为true时,也会打印response的body数据
        NetworkLoggerPlugin(verbose: true),
        NetworkActivityPlugin(networkActivityClosure: { 
            print($0 == .began ? "正在加载..." : "加载完成")
        })
    ])
  • 自定义plugin(HUDLoading控件):

import UIKit
import Moya
import Result

final class RequestLoadingPlugin: PluginType {
    private let viewController: UIViewController
    private var spinner: UIActivityIndicatorView!

    init(viewController: UIViewController) {
        self.viewController = viewController

        let view = UIView(frame: viewController.view.bounds)
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
        spinner.center = view.center
        view.addSubview(spinner)
        viewController.view.addSubview(view)
    }
    //协议方法
// 在一个请求发起前,可以动态修改URLRequest里的内容,做一些调整,比如重设request的超时时间、缓存策略、Cookies设置、允许移动网络等;
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {

        print("[Network Request] : \(request.url?.absoluteString ?? "")")

        return request
    }
// 发起请求
    func willSend(_ request: RequestType, target: TargetType) {
        print("[Network Request Target] : \(target)")
    }

// 收到服务器响应
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        print("请求完成")
        spinner.superview?.removeFromSuperview()

        guard case let Result.failure(error) = result else { return }

        let alert = UIAlertController(title: "数据请求失败", message: error.errorDescription ?? "未知错误", preferredStyle: .alert)
        alert.addAction(.init(title: "好", style: .cancel, handler: nil))
        viewController.present(alert, animated: true, completion: nil)
    }
// 处理返回数据,可以对数据做一些操作    
    func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {

        print("数据处理")
        return result
    }

总结

民用认为Moya很强劲,可以适用于这么些多多模块项目之网络要被,并且提供plugin,方便灵活,且内置了Alamofire第三仓房,在Swift项目中推荐以。

Demo

https://github.com/BackWorld/MoyaDemo

Demo效果

尽管对君有襄助,别忘了于个或,有问题欢迎在底下留言啄磨。

相关文章

网站地图xml地图