Last active
April 20, 2023 12:31
-
-
Save Tulakshana/48d473a8aefa2d6b5f817f15870ae64f to your computer and use it in GitHub Desktop.
Handling re-direction with URLSession (Swift)
This file contains hidden or 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 UIKit | |
@objc class MyAPI: NSObject { | |
static let keyError: String = "Error" | |
static let keyResult: String = "Result" | |
static let unknownError: String = "Unknown error" | |
static let notificationMyAPIDidEnd = Notification.Name(rawValue: "notificationMyAPIDidEnd") | |
static let notificationMyAPIDidFail = Notification.Name(rawValue: "notificationMyAPIDidFail") | |
// MARK: - Constructor - | |
static let sharedInstance = MyAPI() | |
var session: URLSession? | |
let headers = [ | |
"authorization": "Basic my_authorization_token", | |
"cache-control": "no-cache", | |
] | |
fileprivate override init() { | |
super.init() | |
let sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default | |
session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil) | |
} | |
func myAPICall(urlString: String) { | |
let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL, | |
cachePolicy: .useProtocolCachePolicy, | |
timeoutInterval: 10.0) | |
request.httpMethod = "GET" | |
request.allHTTPHeaderFields = headers | |
let dataTask = session?.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in | |
if (error != nil) { | |
DispatchQueue.main.async { | |
NotificationCenter.default.post(name: MyAPI.notificationMyAPIDidFail, object: [MyAPI.keyError:(error?.localizedDescription ?? MyAPI.unknownError)]) | |
} | |
} else { | |
if let httpResponse: HTTPURLResponse = response as? HTTPURLResponse { | |
if (httpResponse.statusCode >= 200) && (httpResponse.statusCode < 300) { | |
if let data = data, | |
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { | |
if let resultDict: [String:Any] = json { | |
if resultDict.count > 0 { | |
let responseDic: [String: Any] = [MyAPI.keyResult: resultDict] | |
DispatchQueue.main.async { | |
NotificationCenter.default.post(name: MyAPI.notificationMyAPIDidEnd, object: responseDic) | |
} | |
return | |
} | |
} | |
} | |
} | |
} | |
} | |
}) | |
dataTask?.resume() | |
} | |
} | |
extension MyAPI: URLSessionDelegate, URLSessionTaskDelegate { | |
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Swift.Void) { | |
// The original request was redirected to somewhere else. | |
// We create a new dataTask with the given redirection request and we start it. | |
if let urlString = request.url?.absoluteString { | |
self.myAPICall(urlString) | |
} else { | |
DispatchQueue.main.async { | |
NotificationCenter.default.post(name: MyAPI.notificationMyAPIDidFail, object: [MyAPI.keyError:MyAPI.unknownError]) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment