Created
December 14, 2018 16:17
-
-
Save ankitthakur/428f39f1a0e2c6b7d3214315e74c7f22 to your computer and use it in GitHub Desktop.
Swift Network Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Network:NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate { | |
internal static let sharedInstance = Network() | |
fileprivate var networkParams:Array<NetworkParams> = Array() | |
fileprivate func networkCall(_ request:URLRequest, completionBlock:@escaping NetworkCompletionBlock) | |
{ | |
let configurationId = String(format: "Network%d", arc4random()) | |
let configuration = URLSessionConfiguration.background(withIdentifier: configurationId) | |
configuration.timeoutIntervalForRequest = request.timeoutInterval | |
configuration.timeoutIntervalForResource = request.timeoutInterval | |
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData | |
configuration.urlCache = nil | |
configuration.allowsCellularAccess = true | |
if #available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *) { | |
configuration.waitsForConnectivity = true | |
} | |
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.current) | |
let task = session.dataTask(with: request) | |
task.resume() | |
let param = NetworkParams() | |
param.urlSession = session | |
param.completionBlock = completionBlock | |
param.request = request | |
networkParams.append(param) | |
let newtask = URLSession.shared.dataTask(with: request) { data, response, error in | |
if let error = error { | |
print("handleClientError: \(error)") | |
return | |
} | |
guard let httpResponse = response as? HTTPURLResponse, | |
(200...299).contains(httpResponse.statusCode) else { | |
print("handleClient response: \(response)") | |
return | |
} | |
if let mimeType = httpResponse.mimeType, mimeType == "text/html", | |
let data = data, | |
let string = String(data: data, encoding: .utf8) { | |
print("response:\(string)") | |
} | |
} | |
newtask.resume() | |
} | |
fileprivate func post(_ postData:Data, request:URLRequest, completionBlock:@escaping NetworkCompletionBlock) | |
{ | |
var request = request | |
request.httpBody = postData as Data | |
request.httpMethod = "POST" | |
networkCall(request, completionBlock: completionBlock) | |
} | |
fileprivate func get(_ postData:Data?, _ request:URLRequest, completionBlock:@escaping NetworkCompletionBlock) | |
{ | |
var request = request | |
request.httpMethod = "GET" | |
if (nil != postData){ | |
request.httpBody = postData | |
} | |
networkCall(request, completionBlock: completionBlock) | |
} | |
// MARK: Public APIs | |
func get(_ postData:Data?, _ urlSring:String, timeout:TimeInterval,completionBlock:@escaping NetworkCompletionBlock) | |
{ | |
let url = URL(string: urlSring) | |
var request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: timeout) | |
request.httpMethod = "GET" | |
if (nil != postData){ | |
request.httpBody = postData | |
} | |
networkCall(request, completionBlock: completionBlock) | |
} | |
func get(_ postData:Data?, _ urlSring:String, headers:[String:String], timeout:TimeInterval, completionBlock:@escaping NetworkCompletionBlock){ | |
let url = URL(string: urlSring) | |
var request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: timeout) | |
for key in headers.keys { | |
request.setValue(headers[key], forHTTPHeaderField: key) | |
} | |
get(postData, request, completionBlock: completionBlock) | |
} | |
func post(_ urlSring:String, body:Data, timeout:TimeInterval, completionBlock:@escaping NetworkCompletionBlock){ | |
let url = URL(string: urlSring) | |
let request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: timeout) | |
post(body, request: request, completionBlock: completionBlock) | |
} | |
func post(_ urlSring:String, body:Data, headers:[String:String], timeout:TimeInterval, completionBlock:@escaping NetworkCompletionBlock){ | |
let url = URL(string: urlSring) | |
var request = URLRequest(url: url!, cachePolicy: URLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: timeout) | |
for key in headers.keys { | |
request.setValue(headers[key], forHTTPHeaderField: key) | |
} | |
post(body, request: request, completionBlock: completionBlock) | |
} | |
//MARK:- Delgates | |
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?){ | |
let params = networkParams.filter { | |
$0.urlSession == session | |
} | |
if params.count > 0 { | |
let param:NetworkParams? = params.last! as NetworkParams | |
if (param != nil){ | |
param!.completionBlock!(param?.responseData, task.response, error as NSError?) | |
} | |
} | |
} | |
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Swift.Void){ | |
completionHandler(.allow) | |
} | |
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data){ | |
let params = networkParams.filter { | |
$0.urlSession == session | |
} | |
if params.count > 0 { | |
let param:NetworkParams? = params.last! as NetworkParams | |
if (param != nil){ | |
if param!.responseData == nil { | |
param!.responseData = NSMutableData(capacity: 0) | |
} | |
param!.responseData?.append(data) | |
} | |
} | |
} | |
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){ | |
var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling | |
var credential:URLCredential? | |
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { | |
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) | |
if (credential != nil) { | |
disposition = URLSession.AuthChallengeDisposition.useCredential | |
} | |
else{ | |
disposition = URLSession.AuthChallengeDisposition.performDefaultHandling | |
} | |
} | |
else{ | |
disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge | |
} | |
completionHandler(disposition, credential) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
internal typealias NetworkCompletionBlock = (_ data:NSMutableData?, _ response:URLResponse?, _ error:NSError?) -> (Void) | |
internal class NetworkParams { | |
var urlSession:URLSession? | |
var task:URLSessionTask? | |
/** | |
* request, for which the connection is made | |
*/ | |
var request:URLRequest? | |
/** | |
* server response block | |
*/ | |
var completionBlock:NetworkCompletionBlock? | |
/** | |
* responseData is binary data, when status is SUCCESS/200 | |
*/ | |
var responseData:NSMutableData? | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Network.sharedInstance.get(nil, "https://www.nasa.gov/rss/dyn/shuttle_station.rss", headers: [:], timeout: 20) { (data, response, error) -> (Void) in | |
print("response:\(String(data: data as! Data, encoding: .utf8))") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment