Coder Social home page Coder Social logo

apiclient's Introduction

APIClient

cocoapods swift Platform License

Integration (Cocoapods)

There're three podspecs:

  • APIClient/Core contain pure interface / types used to abstract from implementation. Use it only in case you're about to provide custom implementation of request executor.
  • APIClient/Alamofire contain AlamofireRequestExecutor implementation.

Usage

Any requests should be made through APIClient's instance. It's constructor requires specifying at least request executor. In case of APIClient/Alamofire it's AlamofireRequestExecutor (that in turn initialized with base url to your server and optioanlly SessionManager that could be customized if needed). You could also provide a list of plugins that will be used by that client (by default you got ErrorPreprocessorPlugin(errorPreprocessor: NetworkErrorProcessor()) so don't forget to include it in case you're using own list) and deserializer (which is JSONDeserializer by default).

Next step is to declare your request. Requests are pure objects(values) that used to provide required data. Your request should conform to one of the three available types: APIRequest, DownloadAPIRequest, or MultipartAPIRequest (names corresponds to their roles). Both DownloadAPIRequest and MultipartAPIRequest are inherited from APIRequest so you can provide any required data (like headers, parameters, encoding etc). You must at least specify path for basic request.

Finally, you call execute(request:parser:completion: method of your client in order to execute your request. Here you also have to specify parser (an instance of ResponseParser protocol). You got DecodableParser and You got JSONParser out of the box.

PluginType

APIClient adopted plugins behavior that allows you to have almost complete control over it's execution flow. You can define your own plugin (by implementation of PluginType protocol and passing it to client through constructor) that will replace/modify/log/resolve/decorate etc any passing request. Refer to PluginType to find documented list of methods.

APIClient also include some basic plugins.

AuthorizationPlugin

allows you to authorize your requests by passing token in it's headers. To use it you need to provide AuthorizationCredentialsProvider to the plugin and mark your request as authorizable by implementing emtpy protocol AuthorizableRequest.

RestorationTokenPlugin

allows you to restore your session in case of token expiration. To use it you need to provide AccessCredentialsProvider (used to obtain token-related information; it also has callbacks to handle restoration results) and callback to provide executed restoration request's result.

LoggingPlugin

simply logs any entries to the plugin using optionally provided closure.

ErrorDecoratorPlugin

used to decorate (e.g. map) incoming error NetworkError to custom type.

ErrorRecovererPlugin

allows use to simplify error recovering flow

ErrorPreprocessorPlugin

allows you to process pure ((httpResponse: HTTPURLResponse, data: Data)) response and create appropriate error.

By default, APIClient uses ErrorPreprocessorPlugin(errorPreprocessor: NetworkErrorProcessor()) which allows us to create NetworkError.response in case of unhandled errors.

Version history

Version Swift Dependencies iOS
2.9.1 5.0 Alamofire 4.9, YALResult 1.4 10
2.9 5.0 Alamofire 4.8, YALResult 1.4 10
2.8 4.2 Alamofire 4.7, YALResult 1.1 10
2.0.1 4.2 Alamofire 4.6, YALResult 1.0 10
1.1.3 4.0 Alamofire 4.6, BoltsSwift 1.4, ObjectMapper 3.3 9
1.0.7 3 Alamofire 4, BoltsSwift 1.3, ObjectMapper 2.0 9

apiclient's People

Contributors

aeugene avatar darthrumata avatar rnkyr avatar serejahh avatar sergey-prikhodko avatar tykhonkov avatar vodolazkyi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apiclient's Issues

dependency "APIClient" has no shared framework schemes for any of the platforms: iOS

It was working fine till Xcode 10.1 and Swift 4.2. Once I updated Xcode to 10.2.1 which support Swift 5.0, I started getting this error. I using Carthage manage dependencies.

Your Environment

  • Version of the component: 2.8
  • Swift version: 5.0
  • iOS version: 12.2.0
  • Device: n/a
  • Xcode version: 10.2.1
  • If you use Cocoapods: n/a
  • If you use Carthage: 0.33.0

Project that demonstrates the bug

Please add a link to a project we can download that reproduces the bug.

empty response parsing

in case there's an empty response APIClient couldn't parse it and sends errors:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}

need to handle the case in JSONDeserializer:

func deserialize(_ response: HTTPURLResponse, data: Data) throws -> AnyObject {
        do {
           ...
        } catch {
            if (error as NSError).code == 3840 { // empty response
                return .success(NSArray())
            }
               ...
        }
    }

error parsing

currently, NetworkError being parsed only in case there's no body in response:

request.responseJSON(completionHandler: { response in
	guard let httpResponse = response.response, let data = response.data else {
	    AlamofireRequestExecutor.defineError(response.error, completion: completion)
	    return
	}

	completion(.success((httpResponse, data)))
})

in that case flow goes to APIClient and it invalidates response due to header (validateResult method)

Authorization plugin

Simple auth plugin is required. In case client won't use exchange tokens flow, the implementation of RestorationTokenPlugin is required only to provide auth token and looks like the following:

extension UserSessionController: AccessCredentialsProvider {
    
    public var accessToken: String? {
        get { return userSession.userMetadata.accessToken }
        set { /* no-op; we're not using session restoration flow */ }
    }
    
    public var exchangeToken: String? {
        get { return nil }
        set { }
    }
    
    public func commitCredentialsUpdate(_ update: (AccessCredentialsProvider) -> Void) {
        // no-op; we're not using session restoration flow
    }
    
    public func invalidate() {
        // no-op; we're not using session restoration flow
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.