概述
有 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
Swift 版本:4.2