IOS intercepts all network traffic from my application?

I want to add a proxy for all network calls from my application. Sort of

func intercept(request: URLRequest) {
  if isOk(request) {
    return // the request continues as normally
  } else if isIntercepted(request) {
    let res = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/2", headerFields: ["Content-Type": "application/json"])
    res.value = "{\"ok\":true}" // not that exactly work, but you get the idea
    request.end(res)
  } else {
    let res = HTTPURLResponse(url: url, statusCode: 401, httpVersion: "HTTP/2")
    res.value = "forbidden"
    request.end(res)
  }
}

I would like it to apply to all calls coming from my application. Those. from my code and from all the libraries and frameworks that I use. Is it possible?

I found questions about reading traffic from other applications (failed) and setting delegates for calls running from my code. I would like to go further with something that 1) will automatically apply to all traffic and 2) enable traffic from third parties

+4
source share
1 answer

This is a class assignment URLProtocol.

From Apple docs:

NSURLProtocol URL-, . NSURLProtocol , URL- URL- . URL .

URLProtocol . , , , / , .

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
    guard URLProtocol.registerClass(MyURLProtocol.self) else
    {
        abort()
    }

    return true
}

, URLSession ( !), :

func getURLSessionConfiguration() -> URLSessionConfiguration
{
    let configuration = URLSessionConfiguration.default

    configuration.protocolClasses = [
        MyURLProtocol.self
    ]

    return configuration
}

let session = URLSession(configuration: getURLSessionConfiguration())

, , startLoading() URLProtocol:

override func startLoading()
{
    if self.isOK()
    {
        let error = NSError(domain: "GuardURLProtocol", code: 10, userInfo: [NSLocalizedDescriptionKey: "Connection denied by guard"])
        self.client?.urlProtocol(self, didFailWithError: error)
    }
    else if let task = self.task
    {
        task.resume()
    }
}

, , Apple.

( ), , , . GuardURLProtocol.swift (BlockFPTURLSession), FTP- .

FTP-, :

2017-02-16 23:09:45.846 URLProtocol[83111:7456862] Error: Error Domain=GuardURLProtocol Code=10 "Connection denied by guard" UserInfo={NSLocalizedDescription=Connection denied by guard}

!

+1

Source: https://habr.com/ru/post/1669205/


All Articles