Danoram Danoram - 27 days ago 8
Swift Question

Difference between setting an NSMutableURLRequest header and adding one

I was wondering what the difference between setting a header value and adding a header value to an NSMutableURLRequest is. Sounds sort of obvious but, for example, can't you just use addValue every time? Will setting a header that doesn't exist throw an error? Will adding a header when it already exists in the request overwrite the existing value?

example

let request.NSMutableURLRequest(URL: NSURL(string: "someURL")!)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
...

Answer

I think the discussion in Apple's official doc is quite clear:

addValue

This method provides the ability to add values to header fields incrementally. If a value was previously set for the specified field, the supplied value is appended to the existing value using the appropriate field delimiter. In the case of HTTP, the delimiter is a comma.

setValue

The new value for the header field. Any existing value for the field is replaced by the new value.


setValue replaces. addValue appends with a delimiter