Skip to content

iAmrSalman/APICodable

Repository files navigation

APICodable

CI Status Version License Platform

banner

TO-DOs

  • perform network request
  • easy to switch between multiple services
  • automatically mapping models
  • network status mintoring
  • save incompleted requests when there is no connection
  • perform requests once connected to network
  • serilize response -> force failure

Requirements

  • iOS 9.0+
  • Xcode 9.0+
  • Swift 4.0+

Installation

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

pod 'APICodable'

Usage

1. Create a model (class or struct)

class FirstModel: Codable, Returnable {
    
    struct JSON: Codable {
        var name: String
        var github: String
    }
    
    var origin: String?
    var json: JSON?
    var labelOrigin: String {
        return "IP -> " + (origin ?? "Unkown")
    }
}

2. Create an API base

struct HTTPBin: APIBase {
    
    static var baseURL: String {
        return "https://httpbin.org/"
    }
    
    static var headers: [String: String]? {
        return nil
    }
}

3. Request

Request<Service, Model>.Method(Path, Parameters).onSuccess{...}.onFailure{...} 

Method: GET, POST, PUT or DELETE. onSuccess & onFailure is not mandatory.

GET

parameters -> ?foo=bar

static func requestIP(completionHandler: @escaping (FirstModel) -> Void) {
    
    Request<HTTPBin, FirstModel>.GET("ip").onSuccess(completionHandler).onFailure({ reason in print(reason) })
    
}

POST

HTTP header: Content-Type: application/json

HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}

Request<HTTPBin, FirstModel>.POST("post", parameters: ["name": "@iAmrSalman", "github": "https://github.com/iAmrSalman"])
    .onSuccess { model in
        print("Name: \(model.json?.name),", "github: \(model.json?.github)")
    }
    .onFailure { reason in
        print(reason)
    }

More Control?

Request<HTTPBin, FirstModel>(.post,
                             path: "post",
                             parameters: ["name": "@iAmrSalman", "github": "https://github.com/iAmrSalman"])
    .perform(onSuccess: { model in
        print("Name: \(model.json?.name),", "github: \(model.json?.github)")
    },
             onFaild: { reson in
                print(reson)
                
    })

Author

iAmrSalman, iamrsalman@gmail.com

License

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