Created
December 14, 2024 00:34
-
-
Save marklearst/2003f116a45e9fc00610f920009a8727 to your computer and use it in GitHub Desktop.
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 Foundation | |
| class NetworkManager: NSObject, URLSessionDelegate, URLSessionTaskDelegate { | |
| static let shared = NetworkManager() | |
| lazy var session: URLSession = { | |
| let config = URLSessionConfiguration.default | |
| return URLSession(configuration: config, delegate: self, delegateQueue: nil) | |
| }() | |
| func fetchData(from endpoint: String, completion: @escaping (Data?, Error?) -> Void) { | |
| guard let url = URL(string: endpoint, relativeTo: URL(string: "https://oldserver.com/api")) else { | |
| completion(nil, NSError(domain: "Invalid URL", code: 400, userInfo: nil)) | |
| return | |
| } | |
| let task = session.dataTask(with: url) { data, response, error in | |
| completion(data, error) | |
| } | |
| task.resume() | |
| } | |
| // Handle redirects | |
| func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { | |
| if let oldURL = response.url?.absoluteString, oldURL.contains("oldserver.com") { | |
| var newRequest = request | |
| if let newURL = URL(string: request.url!.absoluteString.replacingOccurrences(of: "oldserver.com", with: "newserver.com")) { | |
| newRequest.url = newURL | |
| } | |
| completionHandler(newRequest) | |
| } else { | |
| completionHandler(request) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is another Swift snippet for redirecting server calls in your iOS app: