A simple HTTP library written in Swift (URLSession Wrapper). It has VIPER like architecture that makes it easy to understand.
- 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
- iOS 12.0+ / macOS 10.14+ / tvOS 12.0+ / watchOS 5.0+
- Xcode 10.2+
- Swift 5+
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
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.
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)
}
}
})
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!)")
}
})
netkit.pauseDownloadRequestBy(taskId: taskId)
netkit.resumeDownloadRequestBy(taskId: taskId)
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)
}
}
})
netkit.pauseUploadRequestBy(taskId: taskId)
netkit.resumeUploadRequestBy(taskId: taskId)
//Cancel given request
netkit.cancelRequestBy(taskId: taskId)
//Cancel all requests
netkit.cancelAllRequests()
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)
}
}
})
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)
}
}
})
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)
}
}
})
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)
netkit.purgeSession(shouldCancelRunningTasks: true)
NetKit is released under the MIT license. See LICENSE for details.