Communicate via HTTP easily in Swift.

Overview

swift-http-client

CI Release CocoaPods Version Carthage compatible Swift Compatibility Platform Compatibility License Twitter

Communicate via HTTP easily in Swift.

Table of Contents

Installation

Swift Package Manager (Recommended)

Package

You can add this package to Package.swift, include it in your target dependencies.

let package = Package(
    dependencies: [
        .package(url: "https://github.com/uhooi/swift-http-client", .upToNextMajor(from: "0.4.0")),
    ],
    targets: [
        .target(
            name: "<your-target-name>",
            dependencies: ["HTTPClient"]),
    ]
)

Xcode

You can add this package on Xcode. See documentation.

CocoaPods

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

pod 'UHIHTTPClient', '~> 0.4.0'

Carthage

This library is available through Carthage. To install it, simply add the following line to your Cartfile:

github "uhooi/swift-http-client" ~> 0.4.0

How to use

You can just import HTTPClient to use it.

  1. Implement a request body structure that conforms to the Encodable protocol. (Optional)
struct RegisterUserRequestBody: Encodable {
    let name: String
    let description: String
}
  1. Implement a response body structure that conforms to the Decodable protocol.
struct RegisterUserResponseBody: Decodable {
    let id: String
}

extension RegisterUserResponseBody {
    func convertToUserID() -> UserID { .init(id: self.id) }
}
  1. Implement a request structure that conforms to the Request protocol.
import HTTPClient

struct RegisterUserRequest: Request {
    typealias ResponseBody = RegisterUserResponseBody
    var path: String { "user/create_user" }
    var httpMethod: HTTPMethod { .post }
    var httpHeaders: [HTTPHeaderField: String]? { [.contentType: ContentType.applicationJson.rawValue] }
}
  1. Create an instance of the HTTPClient class and call the request method.
struct UserID: Identifiable, Equatable {
    let id: String
}
protocol VersatileRepository {
    func registerUser(name: String, description: String, completion: @escaping (Result<UserID, Error>) -> Void)
}
import HTTPClient

final class VersatileAPIClient {
    static let shared = VersatileAPIClient()
    
    private let httpClient = HTTPClient(baseURLString: "https://example.com/api/")
}

extension VersatileAPIClient: VersatileRepository {
    func registerUser(name: String, description: String, completion: @escaping (Result<UserID, Error>) -> Void) {
        let requestBody = RegisterUserRequestBody(name: name, description: description)
        httpClient.request(RegisterUserRequest(), requestBody: requestBody) { result in
            switch result {
            case let .success(responseBody):
                completion(.success(responseBody.convertToUserID()))
            case let .failure(error):
                completion(.failure(error))
            }
        }
    }
}
VersatileAPIClient.shared.registerUser(name: "Uhooi", description: "Green monster.") { result in
    switch result {
    case let .success(userID):
        // Do something.
    case let .failure(error):
        // Do error handling.
    }
}

Contribution

I would be happy if you contribute :)

Comments
  • Support Linux

    Support Linux

    References

    • https://stackoverflow.com/questions/58592508/how-can-i-use-foundations-urlrequest-type-on-linux
    • https://twitter.com/the_uhooi/status/1454269058136772608?s=20
    • https://github.com/uhooi/swift-output-uhooi/blob/3f7940279a956cd3395362fd319ee86773e7bfef/.github/workflows/main.yml
    opened by uhooi 0
  • Add example

    Add example

    Issue

    • close #9

    References

    • https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#onpushpull_requestpaths
    • https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_iddefaultsrun
    opened by uhooi 0
  • Support Swift concurrency

    Support Swift concurrency

    References

    • https://github.com/uhooi/UhooiPicBook/pull/265
    • https://developer.apple.com/documentation/xcode-release-notes/xcode-13_2-release-notes
    • https://qiita.com/YusukeHosonuma/items/f45fe774f1c2d919cd31
    enhancement 
    opened by uhooi 0
  • Add example

    Add example

    References

    Examples

    • https://speakerdeck.com/niw/shi-jian-ios-opunsosupuroziekutofalseshi-mefang?slide=22
    • https://speakerdeck.com/niw/shi-jian-ios-opunsosupuroziekutofalseshi-mefang?slide=23
    • https://github.com/twitter/TwitterTextEditor/tree/master/Examples

    REST API

    • https://twitter.com/the_uhooi/status/1448211749337849857?s=20
    • https://jsonplaceholder.typicode.com/
    documentation 
    opened by uhooi 0
  • Generate XCFramework on release

    Generate XCFramework on release

    Overview

    carthage update --use-xcframeworks command to easily generate XCFramework.

    References

    • https://twitter.com/the_uhooi/status/1448220732731781126?s=20
    • https://github.com/Carthage/Carthage#building-platform-independent-xcframeworks-xcode-12-and-above
    help wanted 
    opened by uhooi 0
Releases(0.6.0)
Owner
I 💚 Swift and developing iOS apps. Hobby: Tennis🎾, Analog game🎲
null
A Swift Package that allows iOS apps to communicate with AltServer.

AltKit allows apps to communicate with AltServers on the same WiFi network and enable features such as JIT compilation.

Riley Testut 45 Sep 8, 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
OBSwiftSocket is a Swift library to be used for communication with OBS Studio via obs-websocket (v5).

OBSwiftSocket OBSwiftSocket is a Swift library to be used for communication with OBS Studio via obs-websocket (v5). obs-websocket v5 specification: ht

Edon 3 Sep 28, 2022
Library for interacting with Graph Store via UrsusHTTP

Swift Graph Store This is a library for reading from/writing to the Urbit GraphStore via the Swift airlock, UrsusHTTP. DISCLAIMER: This is a wildly in

Justin LeBlanc 6 Jul 22, 2022
MVVM project to show AQI of cities via web socket

Air Quality Monitoring Application Swift project with JSON parsing using codable About the application The app consists of live realtime data from the

Pran Kishore 0 Nov 27, 2021
Swish is a networking library that is particularly meant for requesting and decoding JSON via Decodable

Swish Nothing but net(working). Swish is a networking library that is particularly meant for requesting and decoding JSON via Decodable. It is protoco

thoughtbot, inc. 369 Nov 14, 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
Swift HTTP for Humans

Just is a client-side HTTP library inspired by python-requests - HTTP for Humans. Features Just lets you to the following effortlessly: URL queries cu

Daniel Duan 1.4k Dec 30, 2022
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
Swift/Obj-C HTTP framework with a focus on REST and JSON

Now Archived and Forked PMHTTP will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork of PHMT

Postmates Inc. 509 Sep 4, 2022
Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.

SwiftHTTP SwiftHTTP is a thin wrapper around NSURLSession in Swift to simplify HTTP requests. Features Convenient Closure APIs Simple Queue Support Pa

Dalton 1.9k Dec 7, 2022
A barebones Swift HTTP client with automatic JSON response parsing.

HTTP Client A barebones Swift HTTP client with automatic JSON response parsing. Installation Add HTTP Client as a dependency through Xcode or directly

Joe Masilotti 30 Oct 11, 2022
A Swift web framework and HTTP server.

A Swift Web Framework and HTTP Server Summary Kitura is a web framework and web server that is created for web services written in Swift. For more inf

Kitura 7.6k Jan 6, 2023
Tiny http server engine written in Swift programming language.

What is Swifter? Tiny http server engine written in Swift programming language. Branches * stable - lands on CocoaPods and others. Supports the latest

null 3.6k Dec 31, 2022
A lightweight library for writing HTTP web servers with Swift

Taylor Disclaimer: Not actively working on it anymore. You can check out some alternatives Swift 2.0 required. Working with Xcode 7.1. Disclaimer: It

Jorge Izquierdo 925 Nov 17, 2022
Minimalistic Swift HTTP request agent for iOS and OS X

Agent Table of Contents Introduction Usage HTTP Verbs Overloading Method Chaining Response Closure Verbs Methods NSMutableURLRequest Contributing Lice

null 589 Jun 29, 2022
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Envoy 540 Dec 15, 2022
Swift HTTP server using the pre-fork worker model

Curassow Curassow is a Swift Nest HTTP Server. It uses the pre-fork worker model and it's similar to Python's Gunicorn and Ruby's Unicorn. It exposes

Kyle Fuller Archive 397 Oct 30, 2022