Difference between setting an NSMutableURLRequest header and adding one
Asked Answered
D

1

12

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")
...
Depressor answered 23/4, 2015 at 6:40 Comment(0)
B
25

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

Brigham answered 23/4, 2015 at 6:45 Comment(4)
Oh wow ok this has clarified my understanding hugely! unless appending values to current headers I should use set value? In my mind 'addValue' seemed like another term for 'add a header'..Depressor
@Danoram Depends on what you are trying to accomplish. I feel that setValue is enough for most circumstances.Brigham
What if we "setValue" for non existing key? Will crash with unknown key exception I guess!Peeples
No, App won't crash if we put setValue which has not exist but there will no impact to request and response at all. I think setValue should use always. Because when we use header field means already they are defined inside database.Salver

© 2022 - 2024 — McMap. All rights reserved.