All Projects → gmarm → AlamofireURLRequestConfigurable

gmarm / AlamofireURLRequestConfigurable

Licence: MIT license
URLRequestConfigurable for Alamofire - Even cleaner type safe routing

Programming Languages

swift
15916 projects
ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to AlamofireURLRequestConfigurable

Networkingexample
Write a Networking Layer in Swift 4 using Alamofire 5 and Codable
Stars: ✭ 119 (+440.91%)
Mutual labels:  alamofire
WormholyForObjectiveC
Network debugging made easy,This network debugging tool is developed based on the swift version of Wormholy.
Stars: ✭ 21 (-4.55%)
Mutual labels:  alamofire
MockAlamofire
A simple example showing how to override the URLProtocol to return mock data on Alamofire responses. Helpful if you are looking for a simple way to mock an Alamofire response, with out any additional dependencies.
Stars: ✭ 22 (+0%)
Mutual labels:  alamofire
Swift project
原OC项目用swift实现,纯swift项目,可作为学习swift的demo,包含多个自定义控件,并且进行封装网络请求库,结构清晰。
Stars: ✭ 133 (+504.55%)
Mutual labels:  alamofire
Currency Converter Swift3.0 Viper
Calculates money quick and easy way to see live foreign exchange rates (Based on swift 4.2, viper architecture and special thanks to https://github.com/hakanensari/fixer-io for conversion API)
Stars: ✭ 198 (+800%)
Mutual labels:  alamofire
RevivalxUITableView
This source code provides example for UITableView using Alamofire and Haneke.
Stars: ✭ 13 (-40.91%)
Mutual labels:  alamofire
Rxalamofire
RxSwift wrapper around the elegant HTTP networking in Swift Alamofire
Stars: ✭ 1,503 (+6731.82%)
Mutual labels:  alamofire
Convertify
iOS: Convert Spotify links to Apple Music and vice versa
Stars: ✭ 27 (+22.73%)
Mutual labels:  alamofire
Octobook
A simple Gitbook App that offers offline/online gitbooks reading.
Stars: ✭ 199 (+804.55%)
Mutual labels:  alamofire
iOSSwiftStarter
A sample iOS app written in Swift using the VIPER architecture.
Stars: ✭ 73 (+231.82%)
Mutual labels:  alamofire
Wormholy
iOS network debugging, like a wizard 🧙‍♂️
Stars: ✭ 2,010 (+9036.36%)
Mutual labels:  alamofire
Moya
Network abstraction layer written in Swift.
Stars: ✭ 13,607 (+61750%)
Mutual labels:  alamofire
iOSProjects
It's project that contains different applications developed with Swift 5.7 👨‍💻👩🏼‍💻🧑🏿‍💻
Stars: ✭ 122 (+454.55%)
Mutual labels:  alamofire
Opensource
♨️ 分享GitHub优秀开源项目和主流开发使用的网站、解决问题方案收集以及学习网站或资料,涵盖了iOS, macOS X, Blockchain, Flutter, Weex, H5, Games, C++, Script等多方面的内容,其中iOS大致包涵以下内容:音视频;IM和直播;逆向开发;图像相关(OpenGL, Metal, GPUImage);内购(IAP), ApplePay和第三方支付;安全攻防和应用加固, 数据安全和算法;常用第三方库;导航栏和状态栏;侧边菜单;数据持久;蓝牙, 手势指纹面容ID解锁, 图片浏览器, 扫码, 下拉和上拉刷新, 指示器, Toast, Menu, Sensor, Privacy, WebView和进度条, 动画, 选择器, 搜索, 分享, 图片验证码, 设备相关信息, 广告, 高仿项目及Demo等。
Stars: ✭ 123 (+459.09%)
Mutual labels:  alamofire
Moya-Gloss
Gloss bindings for Moya
Stars: ✭ 37 (+68.18%)
Mutual labels:  alamofire
Netclient Ios
Versatile HTTP Networking in Swift
Stars: ✭ 117 (+431.82%)
Mutual labels:  alamofire
Alamofire-Gloss
Gloss bindings for Alamofire
Stars: ✭ 41 (+86.36%)
Mutual labels:  alamofire
Meal
[40시간만에 Swift로 iOS 앱 만들기] 전국 초/중/고등학교 급식 조회 애플리케이션
Stars: ✭ 15 (-31.82%)
Mutual labels:  alamofire
WhatFilm
Simple iOS app using TMDb API and RxSwift
Stars: ✭ 35 (+59.09%)
Mutual labels:  alamofire
BuckoNetworking
iOS Protocol-Oriented Networking in Swift
Stars: ✭ 18 (-18.18%)
Mutual labels:  alamofire

URLRequestConfigurable for Alamofire

Version License Platform

A replacement for Alamofire's URLRequestConvertible for even cleaner and flexible type safe routing.

Wait, but why?

This is an example for URLRequestConvertible taken straight from Alamofire's documentation:

enum Router: URLRequestConvertible {
    case createUser(parameters: Parameters)
    case readUser(username: String)
    case updateUser(username: String, parameters: Parameters)
    case destroyUser(username: String)

    static let baseURLString = "https://example.com"

    var method: HTTPMethod {
        switch self {
        case .createUser:
            return .post
        case .readUser:
            return .get
        case .updateUser:
            return .put
        case .destroyUser:
            return .delete
        }
    }

    var path: String {
        switch self {
        case .createUser:
            return "/users"
        case .readUser(let username):
            return "/users/\(username)"
        case .updateUser(let username, _):
            return "/users/\(username)"
        case .destroyUser(let username):
            return "/users/\(username)"
        }
    }

    // MARK: URLRequestConvertible

    func asURLRequest() throws -> URLRequest {
        let url = try Router.baseURLString.asURL()

        var urlRequest = URLRequest(url: url.appendingPathComponent(path))
        urlRequest.httpMethod = method.rawValue

        switch self {
        case .createUser(let parameters):
            urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
        case .updateUser(_, let parameters):
            urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
        default:
            break
        }

        return urlRequest
    }
}

It's not really easy to understand what's going on here with a quick look, is it? That's because the URL request's configuration is scattered throughout the implementation, also leading to multiple switch statements. This is what the same example looks like when written using URLRequestConfigurable:

enum Router: URLRequestConfigurable {
    case createUser(parameters: Parameters)
    case readUser(username: String)
    case updateUser(username: String, parameters: Parameters)
    case destroyUser(username: String)

    static let baseURLString = "http://example.com"

    // MARK: URLRequestConfigurable
    var urlRequestConfiguration: URLRequestConfiguration {
        switch self {
        case .createUser(let parameters):
            return URLRequestConfiguration(url: "\(Router.baseURLString)/users",
                                           method: .post,
                                           parameters: parameters,
                                           encoding: URLEncoding.default)
        case .readUser(let username):
            return URLRequestConfiguration(url: "\(Router.baseURLString)/users/\(username)",
                                           method: .get)
        case .updateUser(let username, let parameters):
            return URLRequestConfiguration(url: "\(Router.baseURLString)/users/\(username)",
                                           method: .put,
                                           parameters: parameters,
                                           encoding: URLEncoding.default)
        case .destroyUser(let username):
            return URLRequestConfiguration(url: "\(Router.baseURLString)/users/\(username)",
                                           method: .delete)
        }
    }
}

More structured and readable, right? With URLRequestConfigurable, the URL request's configuration is enforced to be declared in one place and one place only. This results in a consistent clean look across all Routers.

Also note that as of version 1.1 all the values but the url can be omitted if not needed, reducing the number of lines used even further.

Let's look at another example from Alamofire:

enum Router: URLRequestConvertible {
    case search(query: String, page: Int)

    static let baseURLString = "https://example.com"
    static let perPage = 50

    // MARK: URLRequestConvertible

    func asURLRequest() throws -> URLRequest {
        let result: (path: String, parameters: Parameters) = {
            switch self {
            case let .search(query, page) where page > 0:
                return ("/search", ["q": query, "offset": Router.perPage * page])
            case let .search(query, _):
                return ("/search", ["q": query])
            }
        }()

        let url = try Router.baseURLString.asURL()
        let urlRequest = URLRequest(url: url.appendingPathComponent(result.path))

        return try URLEncoding.default.encode(urlRequest, with: result.parameters)
    }
}

And again, look how the example is transformed into something more pleasant to the eye with URLRequestConfigurable:

enum Router: URLRequestConfigurable {
    case Search(query: String, page: Int)

    static let baseURLString = "http://example.com"
    static let perPage = 50

    // MARK: URLRequestConfigurable
    var urlRequestConfiguration: URLRequestConfiguration {
        switch self {
        case .Search(let query, let page) where page > 1:
            return URLRequestConfiguration(url: "\(Router.baseURLString)/search",
                                           method: .get,
                                           parameters: ["q": query, "offset": Router.perPage * page],
                                           encoding: URLEncoding.default)
        case .Search(let query, _):
            return URLRequestConfiguration(url: "\(Router.baseURLString)/search",
                                           method: .get,
                                           parameters: ["q": query],
                                           encoding: URLEncoding.default)
        }
    }
}

Usage

Using URLRequestConfigurable is as easy as making your Routers conform to the URLRequestConfigurable protocol. You can then use Alamofire normally to perform the requests like before:

Alamofire.SessionManager.default.request(Router.get())
.responseJSON { response in
    if let JSON = response.result.value {
        print("JSON: \(JSON)")
    }
}

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

If you want to get results back from GiantBomb (optional), you will need to create your own GiantBomb API key here.

Requirements

  • Alamofire
  • iOS 10.0+ / Mac OS X 10.12+ / tvOS 10.0+ / watchOS 3.0+
  • Xcode 11+

Installation

Swift Package Manager

AlamofireURLRequestConfigurable is available through Swift Package Manager. To install it, simply go to Xcode under File > Swift Packages > Add Package Dependency...

CocoaPods

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

Swift 5.1

pod 'AlamofireURLRequestConfigurable', '~> 1.2'

Swift 3.0

pod 'AlamofireURLRequestConfigurable', '~> 1.1'

Swift 2.x

pod 'AlamofireURLRequestConfigurable', '1.0.1'

Author

George Marmaridis

License

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

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].