2017-02-10 78 views
0

我试图使用NSURLProtocol记录Swift 2.3项目中的所有请求。然而并非所有的URL请求都被记录。具体而言,所有Alamofire请求都没有被记录。Swift - 在mac应用程序中记录所有请求

示例代码

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 
    } 
} 

回答

0

我想这是因为Alamofire使用新的API URLSession,这是不是受NSURLProtocol.registerProtocol电话。

您必须创建一个URLSessionURLSessionConfiguration,其protocolClasses阵列设置为[TestURLProtocol.self]

但有了这个,你将不得不使用自定义的SessionManager来记录请求,而不是使用我认为的隐含的Alamofire.request

+0

我试图从这个响应中使用方法,它没有工作。 http://stackoverflow.com/a/28720198/1449607 – datinc

+0

是的,但你必须在会话管理器中注入配置,然后使用它来代替'Alamofire.request' – Alistra

+0

我正在尝试监视第三方服务。我正在寻找一种解决方案,可以让我监控这些请求,而无需修改代码。 – datinc

0

我最终使用的是pod OHHTTPStubs。我将下面的代码添加到我的应用程序委托来记录每个正在使用的主机。

func applicationDidFinishLaunching(aNotification: NSNotification) { 
    var hosts = [String: Int]() 

    stub({ req in 
     if let url = req.URL, let host = url.host{ 
      var count = 1 
      if let c = hosts[host]{ 
       count = c + 1 
      } 
      hosts[host] = count 

      print("Request #\(count): Host = \(host)") 
     } 
     return false 
     }, 
     response:{_ in return OHHTTPStubsResponse()} 
    ); 
} 
相关问题