2017-09-19 64 views
0

在我的應用程序中,在進行API調用時,我需要在標頭中傳遞位置。但關鍵是轉換爲CamelCase。請找我的代碼如下NSMutableURLRequest forHTTPHeaderField鍵未正確設置

let session = URLSession.shared 
let request = NSMutableURLRequest(url: url!) 
request.httpMethod = "GET" 

request.addValue("XYZLocation", forHTTPHeaderField: "location") 

let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in 

    if (error == nil){ 
     let str = String(data: data!, encoding: String.Encoding.utf8) 
     print("Response : \(String(describing: str))") 
    } 
    else{ 
     print("Error : \(String(describing: error?.localizedDescription))") 
    } 
}) 
print("Header : \(String(describing: request.allHTTPHeaderFields))") 
task.resume() 

日誌輸出低於

Header : Optional(["Location": "XYZLocation"]) 

我怎樣才能保持頭鍵區分大小寫。請幫幫我。

+0

首先,使用本地Swift等價物,'URLRequest'而不是'NSMutableURLRequest'。其次,如果您查看'addValue'的[documentation](https://developer.apple.com/documentation/foundation/nsmutableurlrequest/1407676-addvalue),您可以看到標題值對符合大小寫不敏感到HTTP RFC,所以你也應該在後端使用不區分大小寫的標題。 –

+0

@DávidPásztor與'URLRequest'也是一樣的。我們也無法對後端進行更改。爲什麼只有'Location'標題。它適用於其他標題鍵。 –

回答