我正在使用
连接到服务器的iOS应用程序(Swift 4(Stream.getStreamsToHost(withName: self.host!, port: self.port!, inputStream: &self.inputStream, outputStream: &self.outputStream)
if let instream = self.inputStream, let outstream = self.outputStream {
instream.delegate = self
outstream.delegate = self
instream.schedule(in: .current, forMode: .commonModes)
outstream.schedule(in: .current, forMode: .commonModes)
instream.open()
outstream.open()
}
如果由于某种原因无法到达我的Internet连接不良/无法到达连接/服务器,我想向用户显示错误消息。这已经有效,但是需要将几乎一分钟的错误直到"操作无法完成。
我可以以某种方式减少应用程序中的超时,还是无法更改的系统范围?
stream.setProperty的常数不要接缝任何与超时相关的内容:https://developer.apple.com/documentation/foundation/foundation/stream-#1666775
我可以想象的解决方法是在x秒之后手动安排功能,如果未建立连接,则可以取消它。这是实现自定义超时的最佳实践吗?
阅读了有关此问题的几个线程后,我决定使用一个计时器,该计时器在n秒后检查成功连接:
Stream.getStreamsToHost(withName: self.host!, port: self.port!, inputStream: &self.inputStream, outputStream: &self.outputStream)
if let instream = self.inputStream, let outstream = self.outputStream {
instream.delegate = self
outstream.delegate = self
instream.schedule(in: .current, forMode: .commonModes)
outstream.schedule(in: .current, forMode: .commonModes)
instream.open()
outstream.open()
self.connectionTimer = Timer.scheduledTimer(withTimeInterval: self.CONNECTION_TIMEOUT, repeats: false) { _ in
if !self.instreamReady || !self.outstreamReady {
self.errorHandler(NetworkingError.Timeout("Timeout (self.CONNECTION_TIMEOUT)s exeeded"))
self.disconnect()
}
self.connectionTimer?.invalidate()
self.connectionTimer = nil
}
}
工作:)
var继续= truevar countin = 0
var inp :InputStream?
var out :OutputStream?
let testData = mesaj
Stream.getStreamsToHost(withName: addr, port: port, inputStream: &inp, outputStream: &out)
let stream = out!
print( stream.streamStatus.rawValue)
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
guard continue == true else{
timer.invalidate()
return
}
if (counting == 0){
DispatchQueue.global(qos: .utility).async() {
stream.open()
var position = 0
print( stream.streamStatus.rawValue)
while position < testData.count {
let length = min(4096, testData.count - position)
let amount = testData[position...].withUnsafeBytes {
stream.write($0.bindMemory(to: UInt8.self).baseAddress!, maxLength: length)
}
if amount <= 0 {
// Error or EOF
break
}
position += amount
}
stream.close()
DispatchQueue.main.sync {
self.durumTF.text = "Send to PC"
self.durumTF.textColor = .blue
}
continue=false
}
}
if (counting == 3){
print(stream.streamStatus.rawValue)
if stream.streamStatus.rawValue == 7 {
stream.close()
self.durumTF.text = "Couldn't connect to PC"
self.durumTF.textColor = .red
}
if stream.streamStatus.rawValue == 1 {
stream.close()
self.durumTF.text = "Run server on pc"
self.durumTF.textColor = .red
}
continue = false
}
counting += 1
}