URLRequest HTTPBody没有任何值

时间:2019-04-29 15:54:02

标签: ios swift nsurlrequest

我正在尝试将旧的Swift代码转换为新的Swift代码。我在mutable.HTTPBody上遇到问题,在新代码中没有任何值。是因为我使用的是URLRequest而不是NSMutableURLRequest。我该如何解决?

Swift 2(旧代码):

let mutableURLRequest = NSMutableURLRequest(URL: rootURL.URLByAppendingPathComponent(route.path))

mutableURLRequest.HTTPMethod = method.rawValue
encoding = Alamofire.ParameterEncoding.JSON


let (request, error) = encoding.encode(mutableURLRequest, parameters: route.parameters)

if error != nil { fatalError(error!.description) }

if let mutable: NSMutableURLRequest = request {
    if let key = sessionKey {
        let sessionIdHeader = SessionIdHeader(sessionKey: key, sessionId: sessionId, body: mutable.HTTPBody)
        mutable.setValue(sessionIdHeader.stringValue(), forHTTPHeaderField: "Authorization")
    }
}

return request

快捷键4(新的转换代码):

let url = URL(string: route.path, relativeTo: rootURL)
var mutableURLRequest = URLRequest(url:url!)

mutableURLRequest.HTTPMethod = method.rawValue
encoding = Alamofire.ParameterEncoding.JSON

if let key = sessionKey {
    let sessionIdHeader = SessionIdHeader(sessionKey: key, sessionId: sessionId, body: mutableURLRequest.httpBody)
    mutableURLRequest.setValue(sessionIdHeader.stringValue(), forHTTPHeaderField: "Authorization")
}

return  try encoding.encode(mutableURLRequest, with: route.parameters)

0 个答案:

没有答案