2

I have a swift app. It sends http requests to a server that I cannot access myself.

When the app is at the background for a while, and I return and try to send a request to the server I get an http error "the connection is lost".

I read this post

And I want to add connection:close header and value, as suggested.

I have tried this code:

func taskForGETMethod(method: String, pathParameters: [String], parameters: [String : AnyObject], completionHandler: (result: AnyObject!, error: NSError?) -> Void) -> NSURLSessionDataTask {

    /* 1. Build the URL and configure the request */
    let urlString = Constants.BaseURLSecure + method + HttpClient.escapedPath(pathParameters) + HttpClient.escapedParameters(parameters)
    let url = NSURL(string: urlString)!
    let request = NSURLRequest(URL: url)
    request.setValue("Connection", forKey: "close")

but all my request's are failing now. How can I add the header correctly?

Community
  • 1
  • 1
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

2 Answers2

1

If you want to manipulate the http header values you need to use NSMutableURLRequest and the following API

func setValue(_ value: String?, forHTTPHeaderField field: String)

like so

let url = NSURL(string: "http://yo", relativeToURL: nil)
let req = NSMutableURLRequest(URL: url!)
req.setValue("close", forHTTPHeaderField: "Connection")

Swift 3

let url = URL(string: "http://yo", relativeTo: nil)
let req = NSMutableURLRequest(url: url! )
req.setValue("close", forHTTPHeaderField: "Connection")
Warren Burton
  • 17,451
  • 3
  • 53
  • 73
  • There is an outdated (2005) topic in Apple Mailing Lists, about ignoring "Connection" header in this case - https://lists.apple.com/archives/macnetworkprog/2005/Oct/msg00037.html. Not sure if it still valid or not. – Borys Verebskyi Jan 25 '17 at 14:21
  • 1
    That's really intriguing. I wonder if `NSURLRequest` does the same thing. I should have a look at the actual outbound request some time. – Warren Burton Jan 25 '17 at 19:19
1

The problem is in line

request.setValue("Connection", forKey: "close")

The key is the title of the header, which should be "Connection" and its value should be "close". To put it simple, at the moment you are setting close = Connection and not Connection = close.

You need to change the line to

request.setValue("close", forKey: "Connection")
o15a3d4l11s2
  • 3,969
  • 3
  • 29
  • 40