A Concise HTTP Framework in Swift

Related tags

Networking NetKit
Overview

Language CocoaPods compatible Carthage compatible Build Status

NetKit

A Concise HTTP Framework in Swift.

Requirements

NetKit requires Swift 5.0 and Xcode 10.2

Installation

CocoaPods

You can use CocoaPods to integrate NetKit with your project.

Simply add the following line to your Podfile:

pod "NetKit"

And run pod update in your project directory.

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate NetKit into your Xcode project using Carthage, specify it in your Cartfile:

github "azizuysal/NetKit"

Run carthage update to build the framework and drag the built NetKit.framework into your Xcode project.

Manually

You can integrate NetKit manually into your project simply by dragging NetKit.framework onto Linked Frameworks and Libraries section in Xcode.

Usage

In order to run the included example project, you can install JSON Server. It provides a quick backend for prototyping and mocking on your local machine. A sample db.json file is included in the example project.

Use WebService to create a client for a particular web service and use it to make requests and process responses.

import NetKit

let service = WebService(urlString: "http://localhost:3000/")
service.GET("/posts")
  .responseJSON { json in
    print(json)
    return .Success
  }
  .responseError { error in
    print(error)
  }
  .resume()

responseJSON() is a convenience method and combines obtaining a response and converting to JSON into one step. You can also use response() method to obtain raw response data.

.response { data, response in
  print(String(data: data!, encoding: NSUTF8StringEncoding))
  return .Success
}

You can return .Success or .Failure(ErrorType) from the response handlers to signal error status and control will transfer to .responseError() in case of an error.

Synchronous Requests

You can use resumeAndWait() in order to make a synchronous request.

service.PUT("/posts")
  .setPath(String(post.id))
  .setJSON(post.toJson())
  .responseJSON { json in
    print(json)
    return .Success
  }
  .responseError { error in
    print(error)
  }
  .resumeAndWait()

Authentication and SOAP support

If you need to set additional parameters, headers or authentication handlers, you can do so with Swift method chaining.

weatherService.POST()
  .authenticate { (method, completionHandler) -> WebTaskResult in
    switch method {
    case .Default, .HTTPBasic:
      completionHandler(.UseCredential, NSURLCredential(user: loginId, password: password, persistence: .ForSession))
    default:
      completionHandler(.PerformDefaultHandling, nil)
    }
    return .Success
  }
  .setURLParameters(["op":"GetCitiesByCountry"])
  .setSOAP("<GetCitiesByCountry xmlns=\"http://www.webserviceX.NET\"><CountryName>\(country)</CountryName></GetCitiesByCountry>")
  .response { data, response in
    print(String(data: data!, encoding: NSUTF8StringEncoding))
    return .Success
  }
  .responseError { error in
    print(error)
  }
  .resume()

Support For All Configurations and Task Types

You can easily create WebService instances based on ephemeral or background sessions (the default is based on .defaultSessionConfiguration()).

let service = WebService(urlString: baseURL, configuration: .ephemeralSessionConfiguration())

Just as easily, you can create upload or download tasks (the default is data task).

let task = webService.GET("resource", taskType: WebTask.TaskType.Download)

Background Downloads

You can easily setup a background url session and create file download tasks.

let webService: WebService = {
  let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.azizuysal.netkit.test")
  configuration.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
  let service = WebService(urlString: baseURL, configuration: configuration)
  return service
}()

You can use the convenient file download handler responseFile() to process downloaded files.

downloadService.getFile()
  .responseFile { (url, response) in
    let path = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?
    if let url = url, response = response, filename = response.suggestedFilename, path = path?.URLByAppendingPathComponent(filename) {
      do {
        try NSFileManager.defaultManager().copyItemAtURL(url, toURL: path)
      } catch let error as NSError {
        print(error.localizedDescription)
        return .Failure(error)
      }
    } else {
      return .Failure(WebServiceError.BadData("Bad params"))
    }
    notifyUser(DownloadService.FileDownloaded, filename: response?.suggestedFilename)
    return .Success
  }.responseError { error in
    print((error as NSError).localizedDescription)
    notifyUser(DownloadService.FileDownloaded, error: error)
  }
  .resumeAndWait()

##License

The MIT License (MIT)

You might also like...
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

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

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

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

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

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

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

Http Request wrapper written in Swift

Net Net is a HttpRequest wrapper written in Swift Features GET, POST, PUT, DELETE method Powerful request params: nested params, number, string, dic,

A simple GCD based HTTP client and server, written in 'pure' Swift
A simple GCD based HTTP client and server, written in 'pure' Swift

SwiftyHTTP Note: I'm probably not going to update this any further - If you need a Swift networking toolset for the server side, consider: Macro.swift

Comments
  • Cocoapods

    Cocoapods

    I'd be cool to also add Cocoapods support. I done this implementation myself last week for my library. Just follow this post and this checklist. Lemme know if you need any help! :smile:

    opened by lfarah 2
Owner
Aziz Uysal
Aziz Uysal
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
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
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
libuv base Swift web HTTP server framework

Notice Trevi now open a Trevi Community. Yoseob/Trevi project split up into respective Trevi, lime, middlewares and sys packages at our community. If

leeyoseob 46 Jan 29, 2022
Lightweight, flexible HTTP server framework written in Swift

Hummingbird Lightweight, flexible server framework written in Swift. Hummingbird consists of three main components, the core HTTP server, a minimal we

Hummingbird 245 Dec 30, 2022
A little and powerful iOS framework for intercepting HTTP/HTTPS Traffic.

A little and powerful iOS framework for intercepting HTTP/HTTPS Traffic.

Proxyman 867 Dec 29, 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