Swift - 记录 mac 应用程序中的所有请求

标签 swift swift2 nsurlprotocol

我尝试使用 NSURLProtocol 记录 Swift 2.3 项目中的所有请求。然而,并非所有 URL 请求都会被记录。具体来说,所有 Alamofire 请求都不会被记录。

示例代码

class AppDelegate: NSObject, NSApplicationDelegate{
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        NSURLProtocol.registerClass(TestURLProtocol)
        Alamofire.request(.GET, SomeURL).responseSwiftyJSON({ (request, response, json, error) in })
    }
}

class TestURLProtocol: NSURLProtocol {
    override class func canInitWithRequest(request: NSURLRequest) -> Bool {
        print("request \(request.URL!)") // never called
        return false
    }
}

最佳答案

我认为这是因为 Alamofire 使用新的 URLSession API,它不受 NSURLProtocol.registerProtocol 调用的影响。

您必须使用 URLSessionConfiguration 创建一个 URLSession,并将其 protocolClasses 数组设置为 [TestURLProtocol.self]

但是这样你就必须在任何地方使用自定义的 SessionManager 来记录请求,而不是使用隐式的 Alamofire.request 我认为。

关于Swift - 记录 mac 应用程序中的所有请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42166263/

相关文章:

ios - 如何将依赖项传递给 URL 协议(protocol)子类?

iOS Swift 如何告诉 UIView Controller 我们通过 NSURLProtocol 对象接收到信息

xcode - 将 UIImageView 的形状或大小更改为标准,以在 tableview 中圆形

ios - 嵌套函数上的两个循环导致索引超出范围

ios - 使用 Swift 2 更改 y 位置的 Xcode ScrollView

android - 拦截来自 Android WebView 的*所有*请求

ios - Swift instagram 克隆 : loading followed user post

iOS 9 推送通知 dyld`dyld_fatal_error :

ios - 添加到 MKMapView 时出现 UILongPressGestureRecognizer 问题

ios - 在 Swift Alamofire 中写入的 JSON 类型无效