Danoram Danoram - 1 year ago 133
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?


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

Answer Source

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


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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download