Extensible HTTP Networking for iOS

Related tags

Networking Bridge
Overview

Bridge Carthage compatibleCocoaPods Compatible

Simple Typed JSON HTTP Networking in Swift 4.0

GET

GET<Dict>("http://httpbin.org/ip").execute(success: { (response) in
    let ip: Dict = response
})

let postID = "1"
GET<Dict>("http://jsonplaceholder.typicode.com/posts/#").execute(postID, success: { (response) in
    let post: Dict = response
})

POST

let userComment = ["justin": "wow this is cool"]
let endpoint = POST<[String: AnyObject]>("https://api.bridge.com/comments")
endpoint.execute(params: userComment, success: { (commentResponse: [String: AnyObject]) -> () in
    // Handle success
}, failure: { (error, data, request, response) in
    // Handle failure
})

Interceptors

The power of Bridge is that it lets you create custom "Interceptors" to intercept process your requests before they are sent off to the internets, or to intercept and process your responses before they are returned to the caller's success block.

Attach custom headers based on the endpoint, write retry handling, write authentication handlers, use method tunneling. Interceptors allow Bridge to be extremely extensible to your project needs.

/**
*  Conform to the `ResponseInterceptor` protocol for any Bridge that
*  needs to work with or alter a request before it's sent over the wire
*/
public protocol ResponseInterceptor {
    func process<ReturnType>(endpoint: Endpoint<ReturnType>, inout mutableRequest: NSMutableURLRequest)
}

/**
*  Conform to the `ResponseInterceptor` protocol to work with data after
*  the request is returned with a response.
*/
public protocol ResponseInterceptor {
    func process<ReturnType>(endpoint: Endpoint<ReturnType>, response: NSHTTPURLResponse?, responseObject: ResponseObject) -> ProcessResults
}

Examples:

Object Serialization

Bridge is implemented using generics which allow you to serialize to objects as long as your objects conform to the Parseable protocol.

public protocol Parseable {
    static func parseResponseObject(responseObject: AnyObject) throws -> AnyObject
}

It is left completely up to the developer on how you want to implement the Parseable protocol. You can manually create and serialize your objects:

class User: AnyObject, Parseable {
    var name: String?
    var email: String?
    var pictureURL: NSURL?

    static func parseResponseObject(responseObject: AnyObject) throws -> AnyObject {
        if let dict = responseObject as? Dictionary<String, AnyObject> {
            let user = User()
            user.name = dict["name"] as? String
            user.email = dict["email"] as? String
            user.pictureURL = NSURL(string: dict["avatar_url"] as! String)
            return user
        }
        // If parsing encounters an error, throw enum that conforms to ErrorType.
        throw BridgeErrorType.Parsing
    }
}

Or you can also serialize them using whatever serialization libraries you like. This gist is an example of out out-of-box working solution for Mantle if you're already using Mantle models. No code change is required to your Mantle models.

Once models are setup, making calls are as simple as:

let endpoint = GET<GithubUser>("https://api.github.com/users/rawrjustin")
endpoint.execute(success: { (user: GithubUser) in
    print(user)
})

let endpoint = GET<Array<GithubUser>>("https://api.github.com/users")
endpoint.execute(success: { (users: Array<GithubUser>) in
    print(users)
}, failure: { (error: NSError?) in
    print(error)
})

Advanced Features

Base URL

You can set the base url of your Bridge client

Bridge.sharedInstance.baseURL = "http://api.github.com"
GET<GithubUser>("/users/rawrjustin") // expands to http://api.github.com/users/rawrjustin

Cancellation by Tag

Easily cancel any requests tagged with an identifier.

Bridge.sharedInstance.cancelWithTag("DebouncedSearch")

Variable endpoints

Similar to how Rails maps :id for resources, # is used as the character where a variable would be inserted into the path.

GET<Dict>("/photos/#") will map to /photos/1 if you pass in 1 in the first variadic parameter when you call execute(). You can have multiple variables, they will be mapped in order respectively.

Additional HTTP headers

Endpoint Specific Interceptors

Requirements

  • iOS 8.0+
  • Swift 4.0

Installation

Cocoapods

pod 'Bridge', '0.4.3'

Carthage

github "rawrjustin/Bridge"

License

Bridge is licensed under MIT license.

Questions?

Open an issue

You might also like...
Asynchronous socket networking library for Mac and iOS

CocoaAsyncSocket CocoaAsyncSocket provides easy-to-use and powerful asynchronous socket libraries for macOS, iOS, and tvOS. The classes are described

A delightful networking framework for iOS, macOS, watchOS, and tvOS.
A delightful networking framework for iOS, macOS, watchOS, and tvOS.

AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the Foundation URL Loading System, extending t

foursquare iOS networking library

FSNetworking foursquare's iOS networking library FSN is a small library for HTTP networking on iOS. It comprises a single class, FSNConnection, and se

Lightweight Networking and Parsing framework made for iOS, Mac, WatchOS and tvOS.
Lightweight Networking and Parsing framework made for iOS, Mac, WatchOS and tvOS.

NetworkKit A lightweight iOS, Mac and Watch OS framework that makes networking and parsing super simple. Uses the open-sourced JSONHelper with functio

Bonjour networking for discovery and connection between iOS, macOS and tvOS devices.
Bonjour networking for discovery and connection between iOS, macOS and tvOS devices.

Merhaba Bonjour networking for discovery and connection between iOS, macOS and tvOS devices. Features Creating Service Start & Stop Service Stop Brows

An elegant yet powerful iOS networking layer inspired by ActiveRecord.
An elegant yet powerful iOS networking layer inspired by ActiveRecord.

Written in Swift 5 AlamoRecord is a powerful yet simple framework that eliminates the often complex networking layer that exists between your networki

A networking library for iOS, macOS, watchOS and tvOS

Thunder Request Thunder Request is a Framework used to simplify making http and https web requests. Installation Setting up your app to use ThunderBas

Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Robust Swift networking for web APIs
Robust Swift networking for web APIs

Conduit Conduit is a session-based Swift HTTP networking and auth library. Within each session, requests are sent through a serial pipeline before bei

Comments
  • Installation with Carthage v0.14.0

    Installation with Carthage v0.14.0

    Hi, I get this error when I want to update my Carthage v0.14.0

    *** Fetching Bridge *** Checking out Bridge at "0.3.2" *** xcodebuild output can be found in /var/folders/5y/gz4k3lrj39lf90scpm_q8n480000gp/T/carthage-xcodebuild.Bz3rfZ.log Failed to discover shared schemes in project BridgeTest.xcodeproj — either the project does not have any shared schemes, or xcodebuild timed out.

    If you believe this to be a project configuration error, please file an issue with the maintainers at https://github.com/rawrjustin/Bridge/issues/new

    opened by Sina-KH 3
  • Cookies on response from POST

    Cookies on response from POST

    Hi, Is is possible with your library to actually get cookies from a response? See here for an example of the problem I'm trying to solve. https://github.com/Alamofire/Alamofire/issues/946 Thanks

    opened by andrewjtodd 1
Owner
null
QwikHttp is a robust, yet lightweight and simple to use HTTP networking library for iOS, tvOS and watchOS

QwikHttp is a robust, yet lightweight and simple to use HTTP networking library. It allows you to customize every aspect of your http requests within a single line of code, using a Builder style syntax to keep your code super clean.

Logan Sease 2 Mar 20, 2022
Elegant HTTP Networking in Swift

Alamofire is an HTTP networking library written in Swift. Features Component Libraries Requirements Migration Guides Communication Installation Usage

Alamofire 38.7k Jan 8, 2023
Versatile HTTP Networking in Swift

Net is a versatile HTTP networking library written in Swift. ?? Features URL / JSON / Property List Parameter Encoding Upload File / Data / Stream / M

Intelygenz 124 Dec 6, 2022
🏇 A Swift HTTP / HTTPS networking library just incidentally execute on machines

Thus, programs must be written for people to read, and only incidentally for machines to execute. Harold Abelson, "Structure and Interpretation of Com

John Lui 845 Oct 30, 2022
Simple asynchronous HTTP networking class for Swift

YYHRequest YYHRequest is a simple and lightweight class for loading asynchronous HTTP requests in Swift. Built on NSURLConnection and NSOperationQueue

yayuhh 77 May 18, 2022
ServiceData is an HTTP networking library written in Swift which can download different types of data.

ServiceData Package Description : ServiceData is an HTTP networking library written in Swift which can download different types of data. Features List

Mubarak Alseif 0 Nov 11, 2021
Easy HTTP Networking in Swift a NSURLSession wrapper with image caching support

Networking was born out of the necessity of having a simple networking library that doesn't have crazy programming abstractions or uses the latest rea

Nes 1.3k Dec 17, 2022
🤵🏽‍♀️ Janet — A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveraging the power of async/await.

????‍♀️ Janet — Just another networking kit — A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveragi

Niklas Holloh 3 Sep 6, 2022
Http - Demo for Http Layer

http Example To run the example project, clone the repo, and run pod install fro

null 0 Jan 24, 2022
🌏 A zero-dependency networking solution for building modern and secure iOS, watchOS, macOS and tvOS applications.

A zero-dependency networking solution for building modern and secure iOS, watchOS, macOS and tvOS applications. ?? TermiNetwork was tested in a produc

Bill Panagiotopoulos 90 Dec 17, 2022