Everything work as expected just step-by-step throw debugger, otherwise I'm getting EXC_BAD_ACCESS. I guess that I need a delay somewhere or waiting(preferable) for something.
// 1) Create streams(input/output)
Stream.getStreamsToHost(withName: _host, port: _port, inputStream: &self._input_stream, outputStream: &self._output_stream);
if (self._input_stream == nil || self._output_stream == nil) {
self._promise.reject(HTTPSocketStreamError());
return self._promise;
}
// 2) Delegate to self
self._input_stream!.delegate = self;
self._output_stream!.delegate = self;
// 3) Set dispatch queues
CFReadStreamSetDispatchQueue(_input_stream, DispatchQueue(label: "xyz.httpsocket", attributes: []));
CFWriteStreamSetDispatchQueue(_output_stream, DispatchQueue(label: "xyz.httpsocket", attributes: []));
// 4) Open streams(input/output)
if(!CFReadStreamOpen(_input_stream)) {
close(nil);
self._promise.reject(HTTPSocketStreamError());
return self._promise;
}
if(!CFWriteStreamOpen(_output_stream)) {
close(nil);
self._promise.reject(HTTPSocketStreamError());
return self._promise;
}
let request: CFHTTPMessage = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString, _url as CFURL, kCFHTTPVersion1_1).takeRetainedValue();
self.request(message: request);
if let http_message = CFHTTPMessageCopySerializedMessage(request) {
let data: Data = http_message.takeRetainedValue() as Data;
// need some pause here
let length = data.withUnsafeBytes{
// 5) Write to output stream
_output_stream!.write($0, maxLength: data.count)
}
if (length != 0) {
return self._promise;
}
}
Forgotten "self."
if let http_message = CFHTTPMessageCopySerializedMessage(request) {
let data: Data = http_message.takeRetainedValue() as Data;
// need some pause here
let length = data.withUnsafeBytes{
// 5) Write to output stream
self._output_stream!.write($0, maxLength: data.count)
}