Skip to content

Instantly share code, notes, and snippets.

@kaqu
Created January 26, 2019 17:20
Show Gist options
  • Save kaqu/ecf0334565f4650581d829ecb5814b24 to your computer and use it in GitHub Desktop.
Save kaqu/ecf0334565f4650581d829ecb5814b24 to your computer and use it in GitHub Desktop.
Swift HTTP over Network framework
import Network
let host: NWEndpoint.Host = .init("httpbin.org")
let port: NWEndpoint.Port = .https
let tlsConfig: NWProtocolTLS.Options = .init()
let parameters: NWParameters = .init(tls: tlsConfig)
let connection: NWConnection = .init(host: host, port: port, using: parameters)
connection.stateUpdateHandler = { state in
print("State Update: \(state)")
}
connection.start(queue: DispatchQueue.global())
let method = "GET"
let uri = "/"
let httpVersion = "HTTP/1.1"
let headers = "Host: httpbin.org\r\n"
let body = ""
let rawHTTPRequest = "\(method) \(uri) \(httpVersion)\r\n\(headers)\r\n\(body)"
connection.send(content: rawHTTPRequest.data(using: .ascii), completion: .contentProcessed({ error in
print("Processed, error: \(error)")
connection.receiveMessage { data, _, completed, error in
if let data = data {
print("Response: \(String(data: data, encoding: .ascii)), completed: \(completed), error: \(error)")
} else {
print("Response: nil, completed: \(completed), error: \(error)")
}
}
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment