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

Overview

NetworkKit License MIT

Build Status Available devices Version Carthage compatible

A lightweight iOS, Mac and Watch OS framework that makes networking and parsing super simple. Uses the open-sourced JSONHelper with functional parsing. For networking the library supports basic GET, POST, DELETE HTTP requests.

Install

Cocoapods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To install it, simply add the following line to your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'NetworkKit'

Then run the folloring command:

$ pod install

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 NetworkKit into your Xcode project using Carthage, add it into your Cartfile:

github "imex94/NetworkKit" ~> 1.3

Run carthage update to build the framework and drag the built NetworkKit.framework into your Xcode project under Target - General - Embedded binaries:

Import Framework

Usage

NetworkKitExample project provides a guidance to get started.

For the purpose of this example, let say we want to download one of the stories from Hacker News. For this let's use their API endpoint - https://hacker-news.firebaseio.com/v0/item/11245652.json?print=pretty, which give us the following JSON response:

Run in Postman

{
  "by": "jergason",
  "id": 11245652,
  "kids": [
    11245801,
    11245962,
    11250239,
    11246046
  ],
  "time": 1457449896,
  "title": "CocoaPods downloads max out five GitHub server CPUs",
  "type": "story"
}

We want to deserialize the JSON response above to Swift object. To do this, we need a struct that conforms the protocol Deserializable and implement the required init(data: [String: AnyObject]) constructor and use the deserialization operator (<--):

import NetworkKit
struct NKItem: Deserializable {
    var id: Int?
    var username: String?
    var kids: [Int]?
    var title: String?
    var type: String?
    var date: NSDate?

    init(data: [String : AnyObject]) {
        id <-- data["id"]
        username <-- data["by"]
        kids <-- data["kids"]
        title <-- data["title"]
        type <-- data["type"]
        date <-- data["time"]
    }
}

To connect to an API and perform a GET request is simple and intuitive and parsing is like magic:

NKHTTPRequest.GET(
  "https://hacker-news.firebaseio.com/v0/item/11245652.json",                
  params: ["print": "pretty"],
  success: { data in
      var item: NKItem?
      item <-- data                                        
  },
  failure: { error in
      print(error.message)
  })

API

Networking

GET

A simple HTTP GET method to get request from a url.

urlString - String
The string representing the url.

params (Optional) - [NSObject: AnyObject]?
The parameters you need to pass with the GET method. Everything after '?'.

success - ((AnyObject) -> Void)
Successful closure in case the request was successful.

failure - ((NKHTTPRequestError) -> Void)
Failure Closure which notifies if any error has occurred during the request.

POST

A simple HTTP POST method to post a resource to the url.

urlString - String
The string representing the url.

params (Optional) - [NSObject: AnyObject]?
The body you need to pass with the POST method. Resources you want to pass.

success - ((AnyObject) -> Void)
Successful closure in case the request was successful.

failure - ((NKHTTPRequestError) -> Void)
Failure Closure which notifies if any error has occured during the request.

DELETE

A simple HTTP DELETE method to delete a resource from the server.

urlString - String
The string representing the url.

params (Optional) - [NSObject: AnyObject]?
The body you need to pass with the DELETE method. Resources you want to delete.

success - ((AnyObject) -> Void)
Successful closure in case the request was successful.

failure - ((NKHTTPRequestError) -> Void)
Failure Closure which notifies if any error has occured during the request.

Cancel HTTP Requests

There are error and internet availability checking implemented in the framework, but you can simply cancel any task you want if its needed:

let dataTask = NKHTTPRequest.GET(
  "https://hacker-news.firebaseio.com/v0/item/11245652.json",
  params: ["print": "pretty"],
  success: { data in

  },
  failure: { error in
    print(error.message)
})

dataTask?.cancel()

Parsing

Simple use of parsing can be seen above. There are more advanced options to use

Assigning default values

struct NKItem: Deserializable {
    var id = 0
    var username = ""

    init(data: [String : AnyObject]) {
        id <-- data["id"]
        username <-- data["by"]
    }
}

NSURL Deserialization

let profileImage: NSURL?
profileImage <-- "https://example.com/images/profile_normal.png"

NSDate Deserialization

let date: NSDate?
date <-- 1414172803 // timestamp to NSDate deserialization

Nested JSON

Let's consider a the truncated version of the Twitter API response:

Run in Postman

{
  "text":"Aggressive Ponytail #freebandnames",
  "retweet_count": 2,
  "user":{  
      "name":"Sean Cummings",
      "location":"LA, CA",
      "verified":false,
      "screen_name":"sean_cummings"
  }
}

Where you can just simply create a User and a Tweet structure with a user instance inside:

struct NKTwitterUser: Deserializable {
    var name = ""
    var location = ""
    var verified = false
    var screenName = ""

    init(data: [String : AnyObject]) {
        name <-- data["name"]
        location <-- data["location"]
        verified <-- data["verified"]
        screenName <-- data["screen_name"]
    }
}
struct NKTweet: Deserializable {
    var text = ""
    var retweetCount = 0
    var user: NKTwitterUser?

    init(data: [String : AnyObject]) {
        text <-- data["text"]
        retweetCount <-- data["retweet_count"]
        user <-- data["user"]
    }
}

It's that simple.

License

NetworkKit is available under the MIT license. See the LICENSE file for more info. MIT ⓒ Alex Telek

You might also like...
Lightweight REST library for iOS and watchOS. Available on cococapods
Lightweight REST library for iOS and watchOS. Available on cococapods

RMHttp RMHttp is a Lightweight REST library for iOS and watchOS. Features Chainable Request URL / JSON Parameter Encoding HTTP Methods GET/POST/DELETE

A Swift Multiplatform Single-threaded Non-blocking Web and Networking Framework
A Swift Multiplatform Single-threaded Non-blocking Web and Networking Framework

Serverside non-blocking IO in Swift Ask questions in our Slack channel! Lightning (formerly Edge) Node Lightning is an HTTP Server and TCP Client/Serv

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

Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)
Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)

⚠ Important Notice: Farewell ws... hello Networking ! Networking is the next generation of the ws project. Think of it as ws 2.0 built for iOS13. It u

Parsing Simple HTTP Headers for swift

HTTP Headers Parsing simple HTTP headers using pre-defined header descriptions. Examples: let response = HTTPURLRseponse(..., headers: [ "X-RateLi

iOS/Mac OS framework for Rails
iOS/Mac OS framework for Rails

NSRails is a lightweight framework that makes mapping client-side objects to remote Rails objects a breeze, and calling CRUD operations and others sup

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

Extensible HTTP Networking for iOS

Bridge Simple Typed JSON HTTP Networking in Swift 4.0 GET GETDict("http://httpbin.org/ip").execute(success: { (response) in let ip: Dict = respo

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

Comments
  • Cocoapods please!

    Cocoapods please!

    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 4
Releases(1.4)
Owner
Alex Telek
Co-Founder of @hackcamapp. Former President @kcltech. WWDC 14&15 Student Scholarship recipient. Computer Science grad King’s College London
Alex Telek
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

AFNetworking 33.3k Jan 5, 2023
🌏 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
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

3 SIDED CUBE 16 Nov 19, 2022
SwiftSoup: Pure Swift HTML Parser, with best of DOM, CSS, and jquery (Supports Linux, iOS, Mac, tvOS, watchOS)

SwiftSoup is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very conveni

Nabil Chatbi 3.7k Dec 28, 2022
Lightweight Concurrent Networking Framework

Dots Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements iOS 8.0+ / macOS 10.10+ /

Amr Salman 37 Nov 19, 2022
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

Robbie Hanson 12.3k Jan 8, 2023
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

Abdullah Selek 67 Dec 5, 2022
A lightweight generic networking API written purely in Swift

SwiftyNetworking SwiftyNetworking library is a generic networking library writte

Zaid Rahhawi 0 Dec 24, 2021
ZeroMQ Swift Bindings for iOS, macOS, tvOS and watchOS

SwiftyZeroMQ - ZeroMQ Swift Bindings for iOS, macOS, tvOS and watchOS This library provides easy-to-use iOS, macOS, tvOS and watchOS Swift bindings fo

Ahmad M. Zawawi 60 Sep 15, 2022
A peer to peer framework for OS X, iOS and watchOS 2 that presents a similar interface to the MultipeerConnectivity framework

This repository is a peer to peer framework for OS X, iOS and watchOS 2 that presents a similar interface to the MultipeerConnectivity framework (which is iOS only) that lets you connect any 2 devices from any platform. This framework works with peer to peer networks like bluetooth and ad hoc wifi networks when available it also falls back onto using a wifi router when necessary. It is built on top of CFNetwork and NSNetService. It uses the newest Swift 2's features like error handling and protocol extensions.

Manav Gabhawala 93 Aug 2, 2022