iphone 上的 NSStream 不工作

NSStream on iphone not working

  func connect(host: String, port: Int)
{

    self.host = host
    self.port = port

    NSStream.getStreamsToHostWithName(host, port: port, inputStream: &inputStream, outputStream: &outputStream)

    if inputStream != nil && outputStream != nil
    {
        // Set delegate
        inputStream!.delegate = self
        outputStream!.delegate = self

        // Schedule
        inputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        outputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)

        // Open!
        inputStream!.open()
        outputStream!.open()
    }
}

当我在 XCode 模拟器中启动上面的代码时它可以工作,但是当我在我的 iPhone 上启动它时出现以下错误:

由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'+[NSStream getStreamsToHostWithName:port:inputStream:outputStream:]: 无法识别的选择器发送到 class 0x3b81786c'

getStreamsToHostWithName(_:port:inputStream:outputStream:) in NSStream 不可用 iOS 7. 它在 iOS 中引入 8.

extension NSStream {

    @availability(iOS, introduced=8.0)
    class func getStreamsToHostWithName(hostname: String, port: Int, inputStream: AutoreleasingUnsafeMutablePointer<NSInputStream?>, outputStream: AutoreleasingUnsafeMutablePointer<NSOutputStream?>)
}

您必须改用 CFStreamCreatePairWithSocketToHost

class Connection: NSObject, NSStreamDelegate {

    var inputStream:NSInputStream?
    var outputStream:NSOutputStream?

    func connect(host: String, port: Int) {

        var inStreamUnmanaged:Unmanaged<CFReadStream>?
        var outStreamUnmanaged:Unmanaged<CFWriteStream>?
        CFStreamCreatePairWithSocketToHost(nil, host, UInt32(port), &inStreamUnmanaged, &outStreamUnmanaged)
        inputStream = inStreamUnmanaged?.takeRetainedValue()
        outputStream = outStreamUnmanaged?.takeRetainedValue()

        if inputStream != nil && outputStream != nil {
            // Set delegate
            inputStream!.delegate = self
            outputStream!.delegate = self

            // Schedule
            inputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            outputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)

            // Open!
            inputStream!.open()
            outputStream!.open()
        }
    }