NetworkKit 1.3.2

NetworkKit 1.3.2

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Mar 2016
SPMSupports SPM

Maintained by Alex Telek.



NetworkKit License MIT

Available devices

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

Chartage

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

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.

auth (Optional) - NKOauth?
Add Oauth 2.0 when the API requires one. Just specify the consumerKey and consumer Secret, like this NKOauth(consumerKey: “”, consumerSecret: “”).

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.

auth (Optional) - NKOauth?
Add Oauth 2.0 when the API requires one. Just specify the consumerKey and consumer Secret, like this NKOauth(consumerKey: “”, consumerSecret: “”).

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.

auth (Optional) - NKOauth?
Add Oauth 2.0 when the API requires one. Just specify the consumerKey and consumer Secret, like this NKOauth(consumerKey: “”, consumerSecret: “”).

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