Skip to content

Instantly share code, notes, and snippets.

@marklearst
Created December 14, 2024 00:34
Show Gist options
  • Save marklearst/2003f116a45e9fc00610f920009a8727 to your computer and use it in GitHub Desktop.
Save marklearst/2003f116a45e9fc00610f920009a8727 to your computer and use it in GitHub Desktop.
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)
}
}
}
@marklearst
Copy link
Author

marklearst commented Dec 14, 2024

Here is another Swift snippet for redirecting server calls in your iOS app:

class RedirectProtocol: URLProtocol {
    override class func canInit(with request: URLRequest) -> Bool {
        return request.url?.host == "oldserver.com"
    }
    
    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }
    
    override func startLoading() {
        if let newURL = request.url?.absoluteString.replacingOccurrences(of: "oldserver.com", with: "newserver.com"),
           let url = URL(string: newURL) {
            let newRequest = URLRequest(url: url)
            let session = URLSession.shared.dataTask(with: newRequest) { data, response, error in
                if let response = response, let data = data {
                    self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
                    self.client?.urlProtocol(self, didLoad: data)
                }
                if let error = error {
                    self.client?.urlProtocol(self, didFailWithError: error)
                }
                self.client?.urlProtocolDidFinishLoading(self)
            }
            session.resume()
        }
    }
    
    override func stopLoading() {}
}

// Register the custom URLProtocol
let config = URLSessionConfiguration.default
config.protocolClasses = [RedirectProtocol.self]
let session = URLSession(configuration: config)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment