All Projects → Electrode-iOS → ELWebService

Electrode-iOS / ELWebService

Licence: MIT license
A lightweight HTTP networking framework for Swift

Programming Languages

swift
15916 projects
objective c
16641 projects - #2 most used programming language
c
50402 projects - #5 most used programming language

Projects that are alternatives of or similar to ELWebService

NeumorphismKit
Neumorphism framework for UIKit.
Stars: ✭ 39 (-56.18%)
Mutual labels:  carthage
ivar
Ivar is an adapter based HTTP client that provides the ability to build composable HTTP requests.
Stars: ✭ 14 (-84.27%)
Mutual labels:  http-client
RESTEasy
REST API calls made easier
Stars: ✭ 12 (-86.52%)
Mutual labels:  http-client
spark-sdk-ios
DEPRECATED Particle iOS Cloud SDK. Use -->
Stars: ✭ 52 (-41.57%)
Mutual labels:  carthage
centra
Core Node.js HTTP client
Stars: ✭ 52 (-41.57%)
Mutual labels:  http-client
chclient
Fast http client for SELECT queries in clickhouse
Stars: ✭ 44 (-50.56%)
Mutual labels:  http-client
SSCustomPullToRefresh
SSCustomPullToRefresh is an open-source library that uses UIKit to add an animation to the pull to refresh view in a UITableView and UICollectionView.
Stars: ✭ 62 (-30.34%)
Mutual labels:  carthage
lhc
🚀 Advanced HTTP Client for Ruby. Fueled with interceptors.
Stars: ✭ 32 (-64.04%)
Mutual labels:  http-client
StackBarButtonItem
🔲 StackBarButtonItem can use BarButtonItem like StackView
Stars: ✭ 55 (-38.2%)
Mutual labels:  carthage
Rester
A command line tool to test (REST) APIs
Stars: ✭ 42 (-52.81%)
Mutual labels:  http-client
HypeMachineAPI
No description or website provided.
Stars: ✭ 30 (-66.29%)
Mutual labels:  carthage
SwiftGradients
Useful extensions for UIViews and CALayer classes to add beautiful color gradients.
Stars: ✭ 15 (-83.15%)
Mutual labels:  carthage
curly.hpp
Simple cURL C++17 wrapper
Stars: ✭ 48 (-46.07%)
Mutual labels:  http-client
libashttp
A C++ async HTTP client library to use in asynchronous applications while communicating with REST services.
Stars: ✭ 51 (-42.7%)
Mutual labels:  http-client
NKJMovieComposer
NKJMovieComposer is very simple movie composer for iOS.
Stars: ✭ 40 (-55.06%)
Mutual labels:  carthage
SSAppUpdater
SSAppUpdater is an open-source framework that compares the current version of the app with the store version and returns the essential details of it like app URL, new app version number, new release note, etc. So you can either redirect or notify the user to update their app.
Stars: ✭ 58 (-34.83%)
Mutual labels:  carthage
Ciao
Publish and discover services using Bonjour
Stars: ✭ 50 (-43.82%)
Mutual labels:  carthage
SimplecURL
Easy to use HTTP Client for PHP
Stars: ✭ 14 (-84.27%)
Mutual labels:  http-client
desktop
A native GUI application that makes it easy to explore and test Serverless Framework applications built on AWS Lambda.
Stars: ✭ 42 (-52.81%)
Mutual labels:  http-client
HorizontalStickyHeaderLayout
Horizontal UICollectionViewLayout with Sticky HeaderView
Stars: ✭ 70 (-21.35%)
Mutual labels:  carthage

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].