GithubHelp home page GithubHelp logo

kasukasu-collection / electrode-ios_elwebservice Goto Github PK

View Code? Open in Web Editor NEW

This project forked from electrode-ios/elwebservice

0.0 0.0 0.0 701 KB

A lightweight HTTP networking framework for Swift

License: MIT License

C 0.06% Objective-C 3.42% Swift 96.52%

electrode-ios_elwebservice's Introduction

ELWebService

Build Status Carthage Compatible

ELWebService is an HTTP framework for Swift built on Foundation's URLSession. Designed to integrate cleanly with URLSession, ELWebService avoids using the session delegate events and does not mutate the session's configuration.

Requirements

ELWebService requires Swift 5 and Xcode 10.2.

Installation

Carthage

Install with Carthage by adding the framework to your project's Cartfile.

github "Electrode-iOS/ELWebService"

Manual

Install manually by adding ELWebService.xcodeproj to your project and configuring your target to link ELWebService.framework from ELWebService target.

There are two target that builds ELWebService.framework.

  1. ELWebService: Creates dynamically linked ELWebService.framework.
  2. ELWebService_static: Creates statically linked ELWebService.framework.

Both targets build the same product (ELWebService.framework), thus linking the same app against both ELWebService and ELWebService_static should be avoided.

Usage

Below is a quick overview of how to get started using ELWebService. See the ELWebService Programming Guide for detailed usage information.

Sending HTTP Requests

WebService provides an API for making a HTTP request and processing the response data.

let service = WebService(baseURLString: "https://brewhapi.herokuapp.com/")

service
  .GET("/brewers")
  .setQueryParameters(["state" : "New York"])
  .response { (response: URLResponse?, data: Data?) in
    // process response data
  }
  .resume()

To handle the event of a failure provide a closure for error handling by calling the responseError() method.

let service = WebService(baseURLString: "https://brewhapi.herokuapp.com/")

service
  .GET("/brewers")
  .setQueryParameters(["state" : "New York"])
  .response { (response: URLResponse?, data: Data?) in
    // process response data
  }
  .responseError { (error: ErrorType) in
    // handle error
  }
  .resume()

The error handler will only be called after a request results in an error. If an error occurs all other response handlers will not be called. This pattern allows you to cleanly separate the logic for handling success and failure cases.

Handling JSON responses

Use the responseJSON() method to serialize a successful response as a JSON value of type Any.

let service = WebService(baseURLString: "https://brewhapi.herokuapp.com/")

service
  .GET("/brewers")
  .setQueryParameters(["state" : "New York"])
  .responseJSON { (json: Any, response: URLResponse?) in
    // process response as JSON
  }
  .resume()

Sending URL Query Parameters

Send a GET request with URL query parameters.

let service = WebService(baseURLString: "http://httpbin.org")
let parameters = ["foo" : "bar", "percentEncoded" : "this needs percent encoded"]

service
    .GET("/get")
    .setQueryParameters(parameters)
    .resume()

HTTP

GET /get?percentEncoded=this%20needs%20percent%20encoded&foo=bar HTTP/1.1

Sending Form Data

Send a POST request with form parameter data in the request body.

let service = WebService(baseURLString: "http://httpbin.org")
let parameters = ["foo" : "bar", "percentEncoded" : "this needs percent encoded"]

service
    .POST("/post")
    .setFormParameters(parameters)
    .resume()

HTTP

POST /post HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 55

percentEncoded=this%20needs%20percent%20encoded&foo=bar

Sending JSON

Send a POST request with JSON encoded parameters.

let service = WebService(baseURLString: "http://httpbin.org")

service
    .POST("/post")
    .setJSON(["foo" : "bar", "number" : 42])
    .resume()

HTTP

POST /post HTTP/1.1
Content-Type: application/json
Content-Length: 25

{"number":42,"foo":"bar"}

Error Handling

Error handlers are registered by providing a closure to run in the case the handler chain results in a failure.

service
    .GET("/brewers")
    .responseError { error in
      // I am error
    }
    .resume()

Sometimes your code may fail during processing a response and you will want to handle that failure in an error handler. For example, if you were parsing a JSON payload as an array of model types but the payload failed to be parsed as expected you can use throw to propogate an error of type ErrorType to indicate the parsing failure. When throwing an error from a response handler, all subsequent response handlers in the chain will not run and instead any registered error handlers will be called.

service
    .GET("/brewers")
    .responseJSON { json, response in
        guard let models: [Brewer] = JSONDecoder<Brewer>.decode(json)  {
            throw JSONDecoderError.FailedToDecodeBrewer
        } 

        return .Value(models)
    }
    .responseError { error in
      // handle errors
    }
    .resume()

Objective-C Interoperability

ELWebService supports Objective-C via specially-named response handler methods. See the Objective-C Interoperability section in the ELWebService Programming Guide for more information.

extension ServiceTask {
    internal typealias ObjCResponseHandler = (Data?, URLResponse?) -> ObjCHandlerResult?

    @objc public func responseObjC(handler: (Data?, URLResponse?) -> ObjCHandlerResult?) -> Self

    @objc public func responseJSONObjC(handler: (Any, URLResponse?) -> ObjCHandlerResult?) -> Self

    @objc public func responseErrorObjC(handler: (Error) -> Void) -> Self

    @objc public func updateUIObjC(handler: (Any?) -> Void) -> Self

    @objc public func updateErrorUIObjC(handler: (Error) -> Void) -> Self
}

Mocking

ELWebService provides a simple but flexible mocking API that allows you to mock your web service's underlying session, data tasks, and data task result, the data passed to the data task's completion handler.

let expectation = expectationWithDescription("responseAsBrews handler called when JSON is valid")

// create a mock session
let session = MockSession()

// add a response stub to the session
let brewerJSON = ["name": "Long Trail Brewing Company", "location": "Vermont"]
let mockedResponse = MockResponse(statusCode: 200, json: ["brewers": [brewerJSON]])
session.addStub(mockedResponse)

// inject mock session as your web service's session
let service = WebService(baseURLString: "http://brewhapi.herokuapp.com/")
service.session = session

// make a request that will be fulfilled by the mocked response
service
    .fetchBrewWithBrewID("12345")
    .responseAsBrews { brews in
        XCTAssertEqual(brews.count, 1)
        expectation.fulfill()
    }.updateErrorUI { error in
        XCTFail("updateErrorUI handler should not be called when JSON is valid")
    }
    .resume()


waitForExpectationsWithTimeout(2.0, handler: nil)

For more information on the Mocking API see the mocking section of the ELWebService Programming Guide.

Example Project

An example project is included that demonstrates how ELWebService can be used to interact with a web service. The project uses brewhapi as a mock API for fetching and inserting data. brewhapi is freely hosted at https://brewhapi.herokuapp.com/brews for testing.

electrode-ios_elwebservice's People

Contributors

angelodipaolo avatar nonsensery avatar bsneed avatar dpettigrew avatar steveriggins avatar samgrover avatar cihancimen avatar achordia17 avatar migs647 avatar regnerjr avatar krishpranav avatar sohil avatar

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.