Skip to content

A simple HTTP library written in Swift (URLSession Wrapper)

License

Notifications You must be signed in to change notification settings

Dilip-Parmar/NetKit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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)
  • Retry for all types of request
  • 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, statusCodesForRetry: [Int]? = nil)

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.

statusCodesForRetry - HTTP status codes for retry.

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, maxRetry: Int? = 3, completionBlock: { (urlResponse, result) in
switch result {
    case .failure(let error):
       print("\(error!)")
    case .success(let data):
        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)
}, maxRetry: Int? = 3, completionBlock: { (urlResponse, result) in
    switch result {      
      case .success(let url):
        print("\(url!)")
      case .failure(let error):
        print("\(error!)")   
    }
})

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)
}, maxRetry: Int? = 3, completionBlock: { (urlResponse, result) in
   switch result {
    case .failure(let error):
      print("\(error!)")
    case .success(let data):
        if let data = data {
            let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
            print(response)
            print(json)
        }
    }
})

Pause Upload request

netkit.pauseUploadRequestBy(taskId: taskId)

Resume Upload request

netkit.resumeUploadRequestBy(taskId: taskId)

Cancel Request

//Cancel given request
netkit.cancelRequestBy(taskId: taskId)

//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: { (urlResponse, result) in
    switch result {
    case .failure(let error):
      print("\(error!)")
    case .success(let data):
        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: { (urlResponse, result) in
    switch result {
    case .failure(let error):
      print("\(error!)")
    case .success(let data):
        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: { (urlResponse, result) in
    switch result {
    case .failure(let error):
      print("\(error!)")
    case .success(let data):
        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.