Bamboots - Extension 4 Alamofire

Overview

Bamboots: Extension 4 Alamofire

CI Status Version Platform Language Codebeat License Gitter Weibo <3

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

Protocols

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

  • Requestable: Network request protocol, object conforms to this protocol can make network request.
  • Formable: Form protocol. Object conforms to this protocol can be used by the request, download, upload method in Requestable protocol.
    • UploadFormable: Upload Form protocol, Base protocol for upload request form.
      • UploadStreamFormable: Conforming to this protocol to create an upload form that contains a stream object.
      • UploadDataFormable: Conforming to this protocol to create an upload form that contains a data object.
      • UploadFileFormable: Conforming to this protocol to create an upload form that contains a file.
      • UploadMultiFormDataFormable: Conforming to this protocol to create an upload form that contains multiformdata.
    • DownloadFormable: Download Form protocol, Base protocol for download request form.
      • DownloadResumeFormable: Conforming to this protocol to create a download form that can resume a download task.
    • RequestFormable: Conforming to this protocol to create a request form.
  • Loadable: 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.
    • Maskable: Mask protocol for Loadable, View that conforms to this protocol will be treated as mask.
    • Containable: Container protocol for Loadable, Objects conforms to this protocol can be used as container for the mask.
    • Progressable: 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.
  • Messageable: Message protocol.
    • Warnable: Warn protocol. Conforming to this protocol to customize the way of warning messages displayed when error occured.
    • Informable: Inform protocol. Conforming to this protocol to customize the way of inform messages displayed when request done successfully
  • Errorable: Error protocol. Conforming to this protocol to customize the error configuration.
    • JSONErrorable: 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:

  • LoadType: Enum that conforms to Loadable protocol, using case default(container:Containable) case to show MaskView on the container when requesting.
  • UIAlertController+Messageable: With this extension, you can pass a UIAlertController directly into the warn and inform method of DataRequest.
  • UIButton+Loadable: With this extension, you can pass a button directly into the load method of DataRequest.
  • UITableViewCell+Loadable: With this extension, you can pass a cell directly into the load method of DataRequest.
  • UIRefreshControl+Loadable: With this extension, you can pass a UIRefreshControl directly into the load method of DataRequest.
  • UIProgressView+Progressable: With this extension, you can pass a UIProgressView directly into the progress method of DataRequest.
  • UIScrollView+Containable: Extending UIScrollView to conform to Containable protocol.
  • UITableViewCell+Containable: Extending UITableViewCell to conform to Containable protocol.
  • UIViewController+Containable: Extending UIViewController to conform to Containable protocol.
  • ActivityIndicator: Default mask for UITableViewCell and UIButton
  • MaskView: 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 Bamboots 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 Bamboots 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
  • AlamofireCodable: An Alamofire extension which converts JSON response data into swift objects using Codable

Usage

Create a form

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

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

And you can also have extension for specified protocol

extension Formable where Self: UploadFormable {
    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: RequestFormable {
    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 Requestable protocol, in this protocol, we've already implement some methods for you:

  • func request(_ form: RequestFormable) -> DataRequest
  • func download(_ form: DownloadFormable) -> DownloadRequest
  • func download(_ form: DownloadResumeFormable) -> DownloadRequest
  • func upload(_ form: UploadDataFormable) -> UploadRequest
  • func upload(_ form: UploadFileFormable) -> UploadRequest
  • func upload(_ form: UploadStreamFormable) -> UploadRequest
  • func upload(_ form: UploadMultiFormDataFormable, completion: ((UploadRequest) -> Void)?)

Here is the usage of request method:

class LoadableViewController: UIViewController, Requestable {
    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: Loadable = LoadType.none) -> Self

Show mask on UIViewController

request(WeatherForm()).load(load: LoadType.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 Loadable protocol.

class LoadConfig: Loadable {
    init(container: Containable? = nil, mask: Maskable? = MaskView(), inset: UIEdgeInsets = UIEdgeInsets.zero) {
        insetMine = inset
        maskMine = mask
        containerMine = container
    }
    
    func mask() -> Maskable? {
        return maskMine
    }
    
    func inset() -> UIEdgeInsets {
        return insetMine
    }
    
    func maskContainer() -> Containable? {
        return containerMine
    }
    
    func begin() {
        show()
    }
    
    func end() {
        hide()
    }
    
    var insetMine: UIEdgeInsets
    var maskMine: Maskable?
    var containerMine: Containable?
}

Then we can use it as followed:

let load = LoadConfig(container: view, mask:EyeLoading(), 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 Loadable protocol. In this way you can customized everything the Loadable protocol has.

Show mask on UITableView & UIScrollView

let load = LoadConfig(container:self.tableView, mask: ActivityIndicator(), 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: Progressable) -> 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: JSONErrorable>(error: T, warn: Warnable, completionHandler: ((JSONErrorable) -> Void)? = nil) -> Self

And then we can use it as followed:

let alert = UIAlertController(title: "Warning", message: "Network unavailable", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
        
request(WeatherForm()).warn(
    error: WeatherError(),
    warn: alert
)

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: JSONErrorable>(error: T, inform: Informable) -> Self

And then we can use it as followed:

let alert = UIAlertController(title: "Notice", message: "Load successfully", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
request(WeatherForm()).inform(
    error: WeatherInformError(),
    inform: alert
)

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 AlamofireCodable.

Chained calls

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

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

let warn = UIAlertController(title: "Warning", message: "Network unavailable", preferredStyle: .alert)
warn.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))

let inform = UIAlertController(title: "Notice", message: "Load successfully", preferredStyle: .alert)
inform.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))

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

Bonus

Eyeloading

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 Eyeloading in example project.

Example

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

Installation

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

pod 'Bamboots'

Protobuf Support

pod 'Bamboots/BambootsProtobuf'
  • Use apple/swift-protobuf as protobuf data deserialization
  • run protobuf test
    • fist run Example/Protobuf/pbdemo
    • open Example/Bamboots.xcworkspace
    • run command + u

Author

mmoaay, [email protected]

License

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

You might also like...
Simple REST Client based on RxSwift and Alamofire.

RxRestClient Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 10.0+ tvOS 10.

Alamofire Network Layer written in swift 5 using the protocol oriented, combine, UIKit, MVVM.

CoreAPI-iOS This project Contains Alamofire Network layer Based on Protocol Oriented Concept and Combine Framework. It is created with UIKit, Alamofir

A frida tool that capture GET/POST HTTP requests of iOS Swift library 'Alamofire' and disable SSL Pinning.
A frida tool that capture GET/POST HTTP requests of iOS Swift library 'Alamofire' and disable SSL Pinning.

FridaHookSwiftAlamofire A frida tool that capture GET/POST HTTP requests of iOS Swift library 'Alamofire' and disable SSL Pinning. 中文文档及过程 Features Ca

A toolkit for Network Extension Framework

NEKit NEKit is deprecated. It should still work but I'm not intent on maintaining it anymore. It has many flaws and needs a revamp to be a high-qualit

Extension URLRequest With Swift

JHURLRequest extension URLRequest Example func test1() { let url = "https://httpbin.org/get" let dic: [String: Any] = [ "name": "Lilei

A Codable extension to decode arrays and to catch & log all decoding failures
A Codable extension to decode arrays and to catch & log all decoding failures

SafeDecoder A Codable extension to decode arrays and to catch & log all decoding failures Features SafeDecoder makes two improvements for Codable mode

AlamofireObjectMappe - An Alamofire extension which converts JSON response data into swift objects using ObjectMapper

AlamofireObjectMapper An extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper. Usage Given a U

An extension for Alamofire that converts JSON data into Decodable objects.
An extension for Alamofire that converts JSON data into Decodable objects.

Swift 4 introduces a new Codable protocol that lets you serialize and deserialize custom data types without writing any special code and without havin

Alamofire extension for serialize NSData to SwiftyJSON

Alamofire-SwiftyJSON An extension to make serializing Alamofire's response with SwiftyJSON easily. ⚠️ To use with Swift 3.x please ensure you are usin

An Alamofire extension which converts JSON response data into swift objects using EVReflection

AlamofireJsonToObjects 🚨 This is now a subspec of EVReflection and the code is maintained there. 🚨 You can install it as a subspec like this: use_fr

A network extension app to block a user input URI. Meant as a network extension filter proof of concept.
A network extension app to block a user input URI. Meant as a network extension filter proof of concept.

URIBlockNE A network extension app to block a user input URI. Meant as a network extension filter proof of concept. This is just a research effort to

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

AlamofireImage is an image component library for Alamofire

AlamofireImage AlamofireImage is an image component library for Alamofire. Features Image Response Serializers UIImage Extensions for Inflation / Scal

Lightweight network abstraction layer, written on top of Alamofire
Lightweight network abstraction layer, written on top of Alamofire

TRON is a lightweight network abstraction layer, built on top of Alamofire. It can be used to dramatically simplify interacting with RESTful JSON web-

Mock Alamofire and URLSession requests without touching your code implementation
Mock Alamofire and URLSession requests without touching your code implementation

Mocker is a library written in Swift which makes it possible to mock data requests using a custom URLProtocol. Features Requirements Usage Activating

Restofire is a protocol oriented networking client for Alamofire
Restofire is a protocol oriented networking client for Alamofire

Restofire is a protocol oriented networking client for Alamofire. Features Requirements Installation Usage License Features Global Configuration for h

A progressive download manager for Alamofire
A progressive download manager for Alamofire

ALDownloadManager A progressive download manager for Alamofire (Alamofire下载器) The default support breakpoint continues. Sequential Download(顺序下载 ) Dow

This repository contains a detailed sample app that implements VIPER architecture in iOS using libraries and frameworks like Alamofire, AlamofireImage, PKHUD, CoreData etc.
This repository contains a detailed sample app that implements VIPER architecture in iOS using libraries and frameworks like Alamofire, AlamofireImage, PKHUD, CoreData etc.

iOS Viper Architecture: Sample App This repository contains a detailed sample app that implements VIPER architecture using libraries and frameworks li

A sample app that implements MVVM architecture using Swift, ViewModel, Alamofire
A sample app that implements MVVM architecture using Swift, ViewModel, Alamofire

MVVM Architecture Android: Template This repository contains a sample app that implements MVVM architecture using Swift, ViewModel, Alamofire, and etc

Comments
  • uibutton  action

    uibutton action

    thank you for this awesome library but there is a problem in UIButtons because you used an extension for UIbutton we can't add actions from storyboards in any views

    opened by Alfulayt 2
  • Installation issue via Cocoapods

    Installation issue via Cocoapods

    Check List

    • [x] I have read the README.md, but there is no information I need.
    • [x] I have searched in existing issues, but did find a same one.

    Issue Description

    Description

    Install Bamboots via Cocoapods without specify a git url will fail in building.

    Reproduce

    1. Install Bamboots with the podfile config below:
    target 'ProjectName' do
      use_frameworks!
      pod 'Bamboots'
    end
    

    And the result will be:

    Analyzing dependencies
    Downloading dependencies
    Using Alamofire (4.5.1)
    Using AlamofireObjectMapper (4.1.0)
    Using Bamboots (0.5.0)
    Using ObjectMapper (2.2.9)
    Using Realm (3.0.2)
    Using RealmSwift (3.0.2)
    Generating Pods project
    Integrating client project
    Sending stats
    Pod installation complete! There is 1 dependency from the Podfile and 6 total pods installed.
    

    image

    1. Install Bamboots with the podfile config below:
    platform :ios, '10.0'
    target 'ProjectName' do
      use_frameworks!
      pod 'Bamboots', :git => '[email protected]:mmoaay/Bamboots.git'
    end
    

    And the result will be:

    Analyzing dependencies
    Downloading dependencies
    Using Alamofire (4.5.1)
    Using AlamofireCodable (0.1.1)
    Using Bamboots (0.5.0)
    Generating Pods project
    Integrating client project
    Sending stats
    Pod installation complete! There is 1 dependency from the Podfile and 3 total pods installed.
    

    Everything is ok.

    Other Comment

    Found this: https://github.com/CocoaPods/Specs/blob/master/Specs/2/3/e/Bamboots/0.5.0/Bamboots.podspec.json

    opened by sunnyyoung 1
Releases(0.6.0)
Owner
mmoaay
Love everything
mmoaay
An Alamofire extension which converts JSON response data into swift objects using EVReflection

AlamofireJsonToObjects ?? This is now a subspec of EVReflection and the code is maintained there. ?? You can install it as a subspec like this: use_fr

Edwin Vermeer 161 Sep 29, 2022
A network extension app to block a user input URI. Meant as a network extension filter proof of concept.

URIBlockNE A network extension app to block a user input URI. Meant as a network extension filter proof of concept. This is just a research effort to

Charles Edge 5 Oct 17, 2022
Lightweight network abstraction layer, written on top of Alamofire

TRON is a lightweight network abstraction layer, built on top of Alamofire. It can be used to dramatically simplify interacting with RESTful JSON web-

MLSDev 528 Dec 26, 2022
Restofire is a protocol oriented networking client for Alamofire

Restofire is a protocol oriented networking client for Alamofire. Features Requirements Installation Usage License Features Global Configuration for h

Restofire 381 Sep 29, 2022
A progressive download manager for Alamofire

ALDownloadManager A progressive download manager for Alamofire (Alamofire下载器) The default support breakpoint continues. Sequential Download(顺序下载 ) Dow

null 48 May 1, 2022
Alamofire network layer

NVNetworkRequest Alamofire network layer Installation Add this to your Package dependencies: dependencies: [ .package(url: "https://github.com/vin

Vinh Nguyen 0 Nov 19, 2021
Advanced Networking Layer Using Alamofire with Unit Testing

Advanced Networking Layer Using Alamofire with Unit Testing

Ali Fayed 8 May 23, 2022
Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)

⚠ Important Notice: Farewell ws... hello Networking ! Networking is the next generation of the ws project. Think of it as ws 2.0 built for iOS13. It u

Fresh 351 Oct 2, 2022
Simple REST Client based on RxSwift and Alamofire.

RxRestClient Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 10.0+ tvOS 10.

STDev 16 Nov 19, 2022
EasyImplementationAlamoFire - An iOS project to demonstrate the usage of Alamofire in an efficient and organised way.

EasyImplementationAlamoFire Tutorial to demonstrate an efficient way of handling the APIs structure for your iOS Applications. Prerequisites Swift 5 X

null 0 Jan 3, 2022