-
-
Save TyrfingMjolnir/d73c012b9e3110de51d7e5a04ab3b307 to your computer and use it in GitHub Desktop.
Swift HTTP over Network framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = "POST" | |
let uri = "/" | |
let httpVersion = "HTTP/1.1" | |
let headers = "Host: \( host )\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 )" ) // .ascii? utf8 | |
} 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