MBNetwork-Network request can be easier

标签: swift 网络请求 alamofire json 框架
826人阅读 评论(0) 收藏 举报
分类:

MBNetwork

CI Status
Version
License
Platform

MBNetwork is a network request framework based on Alamofire and ObjectMapper, aiming at making network request easier for business development.

Protocols

MBNetwork has made advantages of protocol-oriented programming and abstracted everything that relevant to network request into protocol. Here is the protocol list:

  • MBRequestable: Network request protocol, object conforms to this protocol can make network request.
  • MBFormable: Form protocol. Object conforms to this protocol can be used by the request, download, upload method in MBRequestable protocol.
    • MBUploadFormable: Upload Form protocol, Base protocol for upload request form.
      • MBUploadStreamFormable: Conforming to this protocol to create an upload form that contains a stream object.
      • MBUploadDataFormable: Conforming to this protocol to create an upload form that contains a data object.
      • MBUploadFileFormable: Conforming to this protocol to create an upload form that contains a file.
      • MBUploadMultiFormDataFormable: Conforming to this protocol to create an upload form that contains multiformdata.
    • MBDownloadFormable: Download Form protocol, Base protocol for download request form.
      • MBDownloadResumeFormable: Conforming to this protocol to create a download form that can resume a download task.
    • MBRequestFormable: Conforming to this protocol to create a request form.
  • MBLoadable: Protocol used for showing mask on specified container when requesting (such as add UIActivityIndicatorView on UIViewcontroller’s view when request begins, and remove it when request ends). Object conforms to this protocol can be used by load method of DataRequest.
    • MBMaskable: Mask protocol for MBLoadable, View that conforms to this protocol will be treated as mask.
    • MBContainable: Container protocol for MBLoadable, Objects conforms to this protocol can be used as container for the mask.
    • MBProgressable: Progress protocol for request, Objects conforms to this protocol can get the progress of the request. Object conforms to this protocol can be used by progress method of DataRequest.
  • MBMessageable: Message protocol.
    • MBWarnable: Warn protocol. Conforming to this protocol to customize the way of warning messages displayed when error occured.
    • MBInformable: Inform protocol. Conforming to this protocol to customize the way of inform messages displayed when request done successfully
  • MBErrorable: Error protocol. Conforming to this protocol to customize the error configuration.
    • MBJSONErrorable: Error protocol for JSON data. Conforming to this protocol to customize the error configuration for JSON data.

Mostly you don’t need to care much about these protocols, because we already have many DEFAULT implementations for them. However if you want to customize something, you just need to conform to these protocols and do what you want. Here is some default implementations for these protcols:

  • MBLoadType: Enum that conforms to MBLoadable protocol, using case default(container:MBContainable) case to show MBMaskView on the container when requesting.
  • MBMessageType: Enum that conforms to MBMessageable protocol, using alertController(title: String, message: String? , actions: [UIAlertAction], container: MBContainable) case to show alertController.
  • UIButton+MBLoadable: With this extension, you can pass a button directly into the load method of DataRequest.
  • UITableViewCell+MBLoadable: With this extension, you can pass a cell directly into the load method of DataRequest.
  • UIRefreshControl+MBLoadable: With this extension, you can pass a UIRefreshControl directly into the load method of DataRequest.
  • UIProgressView+MBProgressable: With this extension, you can pass a UIProgressView directly into the progress method of DataRequest.
  • UIScrollView+MBContainable: Extending UIScrollView to conform to MBContainable protocol.
  • UITableViewCell+MBContainable: Extending UITableViewCell to conform to MBContainable protocol.
  • UIViewController+MBContainable: Extending UIViewController to conform to MBContainable protocol.
  • MBActivityIndicator: Default mask for UITableViewCell and UIButton
  • MBMaskView: Default mask for others.

Features

  1. There is no need to inherit any object to get the features it has, and you can extend any features you want without changing the code of MBNetwork itself.
  2. We have Default extension for most of the protocol, so you can easily startup.
  3. And if you have special needs, extend or conform to it.
  4. The API was designed with the principles of Alamofire, So you can also extend it as MBNetwork already have done for you.
  5. Mainly focus on things between business development and Alamofire, not network request itself.

Requirements

  • Alamofire: Elegant HTTP Networking in Swift
  • ObjectMapper: Simple JSON Object mapping written in Swift
  • AlamofireObjectMapper: An Alamofire extension which converts JSON response data into swift objects using ObjectMapper

Usage

Create a form

For business development, most of the requests’ headers are the same, so you can extend it only for once.

extension MBFormable {
    public func headers() -> [String: String] {
        return ["accessToken":"xxx"];
    }
}

And you can also have extension for specified protocol


extension MBFormable where Self: MBUploadFormable {
    public func headers() -> [String: String] {
        return ["accessToken":"xxx", "file":"xxx"];
    }
}

And for other parameters such as url, method, parameters etc.
Each request will has it’s own value, So we create an object and make it conforms to the protocol

struct WeatherForm: MBRequestFormable {
    var city = "shanghai"

    public func parameters() -> [String: Any] {
        return ["city": city]
    }

    var url = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"
    var method = Alamofire.HTTPMethod.get
}

Make a request

All you have to do is conforming to MBRequestable protocol, in this protocol, we’ve already implement some methods for you:

  • func request(_ form: MBRequestFormable) -> DataRequest
  • func download(_ form: MBDownloadFormable) -> DownloadRequest
  • func download(_ form: MBDownloadResumeFormable) -> DownloadRequest
  • func upload(_ form: MBUploadDataFormable) -> UploadRequest
  • func upload(_ form: MBUploadFileFormable) -> UploadRequest
  • func upload(_ form: MBUploadStreamFormable) -> UploadRequest
  • func upload(_ form: MBUploadMultiFormDataFormable, completion: ((UploadRequest) -> Void)?)

Here is the usage of request method:

class LoadableViewController: UIViewController, MBRequestable {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        request(WeatherForm())
    }
}

Show mask when requesting

We have extended DataRequest class of Alamofire and added a load method to it.

func load(load: MBLoadable = MBLoadType.none) -> Self

Show mask on UIViewController

request(WeatherForm()).load(load: MBLoadType.default(container: self))

Show mask on UIButton

request(WeatherForm()).load(load: button)

Notice: The color of UIActivityIndicatorView is the tintColor of UIButton

Show customized mask

Firstly, we create a LoadConfig class conforms to MBLoadable protocol.

class LoadConfig: MBLoadable {
    init(container: MBContainable? = nil, mask: MBMaskable? = MBMaskView(), inset: UIEdgeInsets = UIEdgeInsets.zero) {
        insetMine = inset
        maskMine = mask
        containerMine = container
    }

    func mask() -> MBMaskable? {
        return maskMine
    }

    func inset() -> UIEdgeInsets {
        return insetMine
    }

    func maskContainer() -> MBContainable? {
        return containerMine
    }

    func begin() {
        show()
    }

    func end() {
        hide()
    }

    var insetMine: UIEdgeInsets
    var maskMine: MBMaskable?
    var containerMine: MBContainable?
}

Then we can use it as followed:

let load = LoadConfig(container: view, mask:MBEyeLoading(), inset: UIEdgeInsetsMake(30+64, 15, UIScreen.main.bounds.height-64-(44*4+30+15*3), 15))
request(WeatherForm()).load(load: load)

This is the most powerful usage of the MBLoadable protocol. In this way you can customized everything the MBLoadable protocol has.

Show mask on UITableView & UIScrollView


let load = LoadConfig(container:self.tableView, mask: MBActivityIndicator(), inset: UIEdgeInsetsMake(UIScreen.main.bounds.width - self.tableView.contentOffset.y > 0 ? UIScreen.main.bounds.width - self.tableView.contentOffset.y : 0, 0, 0, 0))
request(WeatherForm()).load(load: load)

Show mask on UITableViewCell (PS: Still in development)

refresh.attributedTitle = NSAttributedString(string: "Loadable UIRefreshControl")
refresh.addTarget(self, action: #selector(LoadableTableViewController.refresh(refresh:)), for: .valueChanged)
tableView.addSubview(refresh)

func refresh(refresh: UIRefreshControl) {
    request(WeatherForm()).load(load: refresh)
}

Loadable UIRefreshControl

这里写图片描述

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView .deselectRow(at: indexPath, animated: false)
    let cell = tableView.cellForRow(at: indexPath)
    request(WeatherForm()).load(load: cell!)
}

We can also support other refresh control such as MJRefresh.

Show progress when requesting

We have extended DownloadRequest and UploadRequest class of Alamofire and added a progress method to it.

func progress(progress: MBProgressable) -> Self

And then we can use it as followed:

这里写图片描述

download(ImageDownloadForm()).progress(progress: progress)

Show warning message if fail

We have extended DataRequest class of Alamofire and added a warn method to it.

func warn<T: MBJSONErrorable>(error: T, warn: MBWarnable = MBMessageType.none, completionHandler: ((MBJSONErrorable) -> Void)? = nil) -> Self

And then we can use it as followed:

这里写图片描述

request(WeatherForm()).warn(error: WeatherError(), warn: MBMessageType.alertController(title: "Warning", message: "Network unavailable", actions: [UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil)], container: self))

Notice: We only have warn for JSON format response now.

Show inform message if success

We have extended DataRequest class of Alamofire and added a inform method to it.

func inform<T: MBJSONErrorable>(error: T, inform: MBInformable = MBMessageType.none) -> Self

And then we can use it as followed:

这里写图片描述

request(WeatherForm()).inform(error: WeatherInformError(), inform: MBMessageType.alertController(title: "Notice", message: "Load successfully", actions: [UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil)], container: self))

Notice: We only have inform for JSON format response now.

JSON to Object

request(WeatherForm()).responseObject(keyPath: "data") { (response: DataResponse<WeatherResponse>) in
    if let value = response.result.value {
        self.weatherResponse = value
        self.tableView.reloadData()
    }
}

For more information, see AlamofireObjectMapper.

Chained calls

All the method mentioned above can be called in a chained manner, such as followed:

let load = LoadConfig(container: view, mask:MBEyeLoading(), inset: UIEdgeInsetsMake(30+64, 15, UIScreen.main.bounds.height-64-(44*4+30+15*3), 15))

let warn = MBMessageType.alertController(title: "Warning", message: "Network unavailable", actions: [UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil)], container: self)

let inform = MBMessageType.alertController(title: "Notice", message: "Load successfully", actions: [UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil)], container: self)

request(WeatherForm()).load(load:load).progress(progress: progress).warn(error: WeatherError(), warn: warn).inform(error: WeatherInformError(), inform: inform)

Bonus

MBEyeloading

这里写图片描述

We’ve written this motion effect when implementing the customized loading, and it’s all implemented with CAAnimationGroup.

If interested, you can check the file MBEyeloading in example project.

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Installation

MBNetwork is available through CocoaPods. To install
it, simply add the following line to your Podfile:

pod "MBNetwork"

Author

mmoaay, mmoaay@sina.com

License

MBNetwork is available under the MIT license. See the LICENSE file for more info.

查看评论

easier cap驱动程序

  • 2015年10月18日 09:31
  • 76.91MB
  • 下载

国产easier cap 驱动 tb最便宜那款

  • 2017年11月02日 21:12
  • 43.36MB
  • 下载

EasierCAP USB电视卡驱动及视频捕捉应用程序 USB007

  • 2018年02月12日 10:33
  • 234.54MB
  • 下载

Easier Done than Said?(字符串问题)

Easier Done than Said? Password security is a tricky thing. Users prefer simple passwords t...
  • zhangzhilai8
  • zhangzhilai8
  • 2013-04-11 13:39:32
  • 419

Can't find the request for http://localhost:8080/****/****.do's Observer

一般这个错是你可能在项目中用到了cxf,在web.xml中cxf的配置中你可能url-pattern配置为/*, 解决办法: 你在客户端删掉web.xml中的cxf配置或者是在mapping中不要...
  • awj3584
  • awj3584
  • 2012-08-21 16:34:46
  • 6516

Cxf开发webservice时遇到Can't find the request for xx's Observer

最近在用CXF开发web service时遇到这个很郁闷的问题。配置一切都正常,启动tomcat也正常,但是当在IE浏览器中输入http://localhost:8080/工程名时http://loc...
  • zhangshufei8001
  • zhangshufei8001
  • 2016-05-19 16:51:26
  • 2273

Cxf webservice Can't find the request for **'s Observer

Cxf webservice Can't find the request for **'s Observer   2011-09-05 23:30:54|  分类: webservice | ...
  • huangchunwju
  • huangchunwju
  • 2012-10-08 17:41:46
  • 3042

Easier Done Than Said? 【杭电-1039】 附题

/* Easier Done Than Said? Problem DescriptionPassword security is a tricky thing. Users prefer simpl...
  • Holyang_1013197377
  • Holyang_1013197377
  • 2014-07-28 19:52:52
  • 662

hdu 1039 - Easier Done Than Said?

题目:给你一个小写字符串,判断是否安全,安全规则如下:             1.包含元音字母;2.相邻3个元素不能都是元音或辅音;3.连续2个字母相同之能是o或e。 分析:简单题。直接模拟即可...
  • mobius_strip
  • mobius_strip
  • 2015-02-09 22:24:49
  • 560

警告: Can't find the request for http://localhost:8080/ibatisSpringDemo/ws/testWS's Observer

标题中的报错是在写一个webservices例子时候报的错误,我直接访问http://localhost:8080/ibatisSpringDemo/ws/testWS?wsdl  后 tomcat中...
  • baoming158
  • baoming158
  • 2014-04-04 12:46:29
  • 1174
    个人资料
    专栏达人 持之以恒
    等级:
    访问量: 33万+
    积分: 5000
    排名: 7045
    博客专栏
    最新评论