iOS会拦截我应用程序中的所有网络流量吗? [英] iOS intercept all network traffic from my app?

查看:61
本文介绍了iOS会拦截我应用程序中的所有网络流量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的应用发出的所有网络通话添加代理.像

I'd like to add a proxy to all networks calls coming from my app. Something like

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'd like it to be applied to all calls coming from my app. Ie from my code and from all libraries and frameworks I'm using. Is it possible?

我发现了一些有关读取其他应用程序流量的问题(不可能),以及如何设置从我的代码开始的呼叫的委托.我想进一步介绍以下内容:1)自动适用于所有流量,而2)包含来自第三方的流量

I've found questions about reading traffic of other apps (not possible) and setting delegates on calls started from my code. I'd like to go further with something that 1) would automatically apply to all traffic and 2) include traffic from 3rd parties

推荐答案

这是 URLProtocol 类的工作.

摘自Apple文档:

NSURLProtocol对象处理协议特定URL的加载数据.NSURLProtocol类本身是一个抽象类,提供用于处理具有特定URL的URL的基础结构方案.您为任何自定义协议或URL方案创建子类您的应用程序支持.

An NSURLProtocol object handles the loading of protocol-specific URL data. The NSURLProtocol class itself is an abstract class that provides the infrastructure for processing URLs with a specific URL scheme. You create subclasses for any custom protocols or URL schemes that your app supports.

您需要实现自己的 URLProtocol 子类,并将其注册到应用程序中才能使用.此后,从应用程序初始化的所有连接都将使用该协议,并且您将能够处理/阻止所需的任何请求.

You need to implement your own subclass of URLProtocol and register it with the app for it to be used. Thereafter all connections initialized from the App will make use of the protocol, and you will be able to handle/block whichever request you want.

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

    return true
}

此外,如果您正在使用 URLSession (并且应该使用!),那么您还必须通过会话配置来注册您的课程:

Also, if you are using URLSession (and you should!), then you also have to register your class through the session configurations:

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

    configuration.protocolClasses = [
        MyURLProtocol.self
    ]

    return configuration
}

let session = URLSession(configuration: getURLSessionConfiguration())

然后,您可以通过 URLProtocol 子类的 startLoading()方法管理要阻止的任何内容:

Then you can manage whatever you want to block from the startLoading() method of your URLProtocol subclass:

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的文档.

There are more methods you have to implement, and you should read the documentation from Apple.

但是,作为一种小玩意儿(以及为自己运动),我已经编写了通用的阻止程序协议,然后应进行检查以了解其工作原理.在 GuardURLProtocol.swift 文件的底部,有一个示例子类( BlockFPTURLSession ),其中所有FTP请求都被架构阻止.

But as a gizmo (and exercise for myself), I have written a generic blocker protocol, and you should check it out to see how it works. In the bottom of the GuardURLProtocol.swift file there is an example subclass (BlockFPTURLSession) where all FTP requests are blocked by schema.

如果您使用上面我链接的类,并尝试打开FTP连接,则会看到以下错误:

If you use the class I linked above, and try to open an FTP connection, you will see the following errors:

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}

玩得开心!

这篇关于iOS会拦截我应用程序中的所有网络流量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆