URLRequest相等不包含httpBody

时间:2018-09-21 09:06:10

标签: swift urlrequest swift4.2

概述

有2个URLRequest,一个带有httpBody,另一个没有httpBody
但是,进行比较时,表明两者相等。

问题

这是预期的行为还是我错过了什么?

代码

let url = URL(string: "www.somevalidURL.com")!

var r1 = URLRequest(url: url)
r1.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")
r1.httpBody = makeBody(withParameters: ["email" : "a@b.com"])

var r2 = URLRequest(url: url)
r2.addValue("Content-Type", forHTTPHeaderField: "application/json; charset=utf-8")

if r1 == r2 {
    print("requests are equal")
}
else {
    print("requests are not equal")
}

if r1.httpBody == r2.httpBody {
    print("body is equal")
}
else {
    print("body is not equal")
}

func makeBody(withParameters bodyParameters: [String : Any]?) -> Data? {
    guard let bodyParameters = bodyParameters,
        !bodyParameters.isEmpty else {
            return nil
    }
    let body : Data?
    do {
        body = try JSONSerialization.data(withJSONObject: bodyParameters,
                                          options: .prettyPrinted)
    }
    catch {
        print("Error in creating Web Service Body = \(error)")
        body = nil
    }
    return body
}

输出

requests are equal
body is not equal

Xcode 10
迅捷版:4.2

2 个答案:

答案 0 :(得分:5)

URLRequest是Foundation类型NSURLRequest的Swift覆盖类型,因此==最终调用了isEqual()方法 NSURLRequest

Foundation库是非Apple平台的开源软件,位于 NSURLRequest.swift#L245我们发现:

open override func isEqual(_ object: Any?) -> Bool {
    //On macOS this fields do not determine the result:
    //allHTTPHeaderFields
    //timeoutInterval
    //httBody
    //networkServiceType
    //httpShouldUsePipelining
    guard let other = object as? NSURLRequest else { return false }
    return other === self
        || (other.url == self.url
            && other.mainDocumentURL == self.mainDocumentURL
            && other.httpMethod == self.httpMethod
            && other.cachePolicy == self.cachePolicy
            && other.httpBodyStream == self.httpBodyStream
            && other.allowsCellularAccess == self.allowsCellularAccess
            && other.httpShouldHandleCookies == self.httpShouldHandleCookies)

所以这似乎是故意的。

答案 1 :(得分:0)

如果您来这里想知道为什么您的相同URLRequest彼此不相等,就像我一样,我发现原因是 URLRequest的等价实现区分了httpBody设置为nil或默认为nil。

如果我们执行以下操作:

let request = URLRequest(url: URL(string: "test.com"))
var expectedRequest = URLRequest(url: URL(string: "test.com"))
expectedRequest.httpBody = nil

然后:

request == expectedRequest //false
print(request.httpBody) // nil
request.httpBody = nil
request == expectedRequest //true

httpBody显式设置为nil将解决此问题。实际上,主体是什么都没有关系,只是它已被明确设置。

request.httpBody = Data()
request == expectedRequest //true

可能的解释

正如马丁正确指出的那样,Swift's source code不包含httpBody。但是,所有(在链接中)相等的属性(都可以作为NSURLRequests强制转换)不会返回true(请参见下面的lldb输出)。我只能假定链接的代码被重写为包括另一个属性,并且在didSet上调用willSethttpBody时会对此属性进行修改 lldb Terminal Log