Skip to content
A simple HTTP library written in Swift (URLSession Wrapper)
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
NetKit.xcodeproj
OSX
Sources/NetKit Resolved swiftlint warnings (#1) Jul 19, 2019
Tests Initial Version(1.0.1) Jul 16, 2019
iOS Initial Version(1.0.1) Jul 16, 2019
tvOS Initial Version(1.0.1) Jul 16, 2019
watchOS/NetKit watchOS Initial Version(1.0.1) Jul 16, 2019
.gitignore Initial commit Jul 16, 2019
.swiftlint.yml Resolved swiftlint warnings (#1) Jul 19, 2019
LICENSE Initial commit Jul 16, 2019
NetKit.podspec update release version Jul 19, 2019
Package.swift Initial Version(1.0.1) Jul 16, 2019
README.md update release version Jul 19, 2019

README.md

NetKit

A simple HTTP library written in Swift (URLSession Wrapper). It has VIPER like architecture that makes it easy to understand.

Table of Contents

Features

  • Singleton free
  • No external dependencies
  • Simple and Configurable Request
  • Single Data Call
  • Resumable Download file request
  • Resumable Upload file request
  • Cancellable requests
  • Network Monitor for network connectivity
  • Request Body/Query Parameters Encoding
  • SSL Certificate Pinning
  • HTTP Basic Authentication
  • HTTP Digest Authentication
  • Request Body Encryption (SHA256)
  • Free

Requirements

  • iOS 12.0+ / macOS 10.14+ / tvOS 12.0+ / watchOS 5.0+
  • Xcode 10.2+
  • Swift 5+

Installation

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

pod 'NetKit', :git => 'https://github.com/Dilip-Parmar/NetKit'

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

github "Dilip-Parmar/NetKit"  "2.0.0" //always use latest release version

NetKit is also available through Swift Package Manager. To install it, simply enter given URL into "Enter Package Repository URL" search field of Xcode.

https://github.com/Dilip-Parmar/NetKit

How to use

Initialization

let netKit = NetKit.init(sessionConfiguration: sessionConfiguration, sessionDelegate: nil, commonHeaders: ["Content-Type":"application/json"], waitsForConnectivity: false, waitingTimeForConnectivity: 300)

It's easy to provide session configuration. The available types are Default, Ephemeral and Background. Use URLSessionConfiguration to get one of the available type.

  • Default - let sessionConfiguration = URLSessionConfiguration.default

  • Ephemeral - let sessionConfiguration = URLSessionConfiguration.ephemeral

  • Background - let sessionConfiguration = URLSessionConfiguration.background(withIdentifier: "CUSTOM UNIQUE IDENTIFIER")

sessionDelegate - You may have such requirement where a controller class should be an instance of URLSessionDelegate instead of Network library itself. NetKit gives that flexibility by using custom delegate.

let commonHeaders = ["Content-Type":"application/json"]

waitsForConnectivity - should NetKit fails immediately or wait for network connectivity.

waitingTimeForConnectivity - in seconds.

Single Request

let queryParames = ["country":"in", "apiKey":"daae11"]
let request = HTTPRequest.init(baseURL: "https://www.google.com", path: "/safe", method: .GET, requestBody: nil, bodyEncoding: nil, requestHeaders: ["Content-Type":"application/json"], queryParams: queryParames, queryParamsEncoding: .default, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60, networkServiceType: .background, bodyEncryption: nil)

let taskId = netkit.send(request: request, authDetail: nil, completionBlock: { (result) in
switch result {
    case .failure(let failure):
    switch failure {
        default:
            break
    }
    case .success(let success):
        switch success {
        case .block(let data, let response):
            if let data = data {
            let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
            print(response)
            print(json)
           }
        }
    }
})

Download File Request

let queryParames = ["country":"in", "apiKey":"daae11"]
let request = HTTPRequest.init(baseURL: "https://www.google.com", path: "/safe", method: .GET, requestBody: nil, bodyEncoding: nil, requestHeaders: ["Content-Type":"application/json"], queryParams: queryParames, queryParamsEncoding: .default, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 120, networkServiceType: .background, bodyEncryption: nil)

let taskId = netkit.sendDownload(request: request, authDetail: nil, progressBlock: { (progress) in
print(progress)
}, completionBlock: { (result) in
    switch result {      
      case .success(let success):
        switch success {
            case .block(let url, let response):
        }
      case .failure(let failure):
        switch failure {
        default:
        }      
    }
})

Pause download request

netkit.pauseDownloadRequestBy(taskId: taskId)

Resume download request

netkit.resumeDownloadRequestBy(taskId: taskId)

Upload File Request

let fileURL = URL.init(fileURLWithPath: "/Users/...../file.jpg")
let taskId = netkit.sendUpload(request: request, fileURL: fileURL, authDetail: nil, progressBlock: { (progress) in
print(progress)
}, completionBlock: { (result) in

})

Pause Upload request

netkit.pauseUploadRequestBy(taskId: taskId)

Resume Upload request

netkit.resumeUploadRequestBy(taskId: taskId)

Cancel Request

//Cancel given request
netkit.cancelRequestBy(taskId: taskId, taskType: .download)

//Cancel all requests
netkit.cancelAllRequests()

SSL Certificate Pinning

let queryParames = ["country":"in", "apiKey":"daae11"]
let request = HTTPRequest.init(baseURL: "https://www.google.com", path: "/safe", method: .GET, requestBody: nil, bodyEncoding: nil, requestHeaders: ["Content-Type":"application/json"], queryParams: queryParames, queryParamsEncoding: .default, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60, networkServiceType: .background, bodyEncryption: nil)

let authDetail = AuthDetail.init(authType: .serverTrust, shouldValidateHost: true, host: "google.com", userCredential: nil, certificateFileName: "my-certificate")

let taskId = netkit.send(request: request, authDetail: authDetail, completionBlock: { (result) in
    switch result {
    case .failure(let failure):
        switch failure {
        default:
            break
        }
    case .success(let success):
        switch success {
        case .block(let data, let response):
            if let data = data {
                let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
                print(response)
                print(json)
            }
        }
    }
})

HTTP Basic Authentication

let queryParames = ["country":"in", "apiKey":"daae11"]
let request = HTTPRequest.init(baseURL: "https://www.google.com", path: "/safe", method: .GET, requestBody: nil, bodyEncoding: nil, requestHeaders: ["Content-Type":"application/json"], queryParams: queryParames, queryParamsEncoding: .default, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60, networkServiceType: .background, bodyEncryption: nil)

let userCredential = URLCredential.init(user: "user", password: "password", persistence: .forSession)

let authDetail = AuthDetail.init(authType: .HTTPBasic, shouldValidateHost: true, host: "google.com", userCredential: userCredential, certificateFileName: nil)

let taskId = netkit.send(request: request, authDetail: authDetail, completionBlock: { (result) in
    switch result {
    case .failure(let failure):
        switch failure {
        default:
            break
    }
    case .success(let success):
    switch success {
        case .block(let data, let response):
            if let data = data {
                let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
                print(response)
                print(json)
            }
        }
    }
})

HTTP Digest Authentication

let queryParames = ["country":"in", "apiKey":"daae11"]
let request = HTTPRequest.init(baseURL: "https://www.google.com", path: "/safe", method: .GET, requestBody: nil, bodyEncoding: nil, requestHeaders: ["Content-Type":"application/json"], queryParams: queryParames, queryParamsEncoding: .default, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60, networkServiceType: .background, bodyEncryption: nil)

let userCredential = URLCredential.init(user: "user", password: "password", persistence: .forSession)

let authDetail = AuthDetail.init(authType: .HTTPDigest, shouldValidateHost: true, host: "google.com", userCredential: userCredential, certificateFileName: nil)

let taskId = netkit.send(request: request, authDetail: authDetail, completionBlock: { (result) in
    switch result {
    case .failure(let failure):
        switch failure {
        default:
            break
        }
    case .success(let success):
        switch success {
        case .block(let data, let response):
            if let data = data {
                let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
                print(response)
                print(json)
            }
        }
    }
})

Network Monitor

Register for these notifications to get notified for network status. NetworkStatusNotification.Available NetworkStatusNotification.Offline

NotificationCenter.default.addObserver(self, selector: #selector(netwokConnected(aNotification:)), name: NSNotification.Name.init(NetworkStatusNotification.Available), object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(waitingForNetwork(aNotification:)), name: NSNotification.Name.init(NetworkStatusNotification.Offline), object: nil)

Destroy Session

netkit.purgeSession(shouldCancelRunningTasks: true)

Author

Dilip Parmar

License

NetKit is released under the MIT license. See LICENSE for details.

TODO:

Unit test cases

You can’t perform that action at this time.