2017-02-10 80 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()} 
    ); 
} 
相關問題