Swift:如何在收听流时更新UI

时间:2016-05-25 05:03:35

标签: swift sockets

下面的代码似乎有效,但我无法在获取流事件后更新button

我已经尝试了delegatedispatch_async,似乎都没有做到这一点。

我在这里错过了什么魔力?

import UIKit

class TestViewController: UIViewController {

    @IBOutlet weak var connectButton: UIBarButtonItem!
    @IBOutlet weak var stopButton: UIBarButtonItem!

    let socket = Socket()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func connectServer(sender: UIBarButtonItem) {
        socket.connect("10.0.0.1", port: 12345)
    }

    func setStopButtonState(state: String) {
        switch state {
        case "go":
            stopButton?.title = "STOP"
            break
        case "stop":
            stopButton?.title = "Start"
            break
        default:
            break
        }
    }
}

class Socket: NSObject, NSStreamDelegate {
    var inputStream: NSInputStream?
    var outputStream: NSOutputStream?

    func connect(host: String, port: Int) {
        NSStream.getStreamsToHostWithName(host, port: port, inputStream: &inputStream, outputStream: &outputStream)
        if inputStream != nil && outputStream != nil {
            inputStream!.delegate = self
            outputStream!.delegate = self
            inputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            outputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            inputStream!.open()
            outputStream!.open()
        }
    }

    func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
        if aStream === inputStream {
            switch eventCode {
            case NSStreamEvent.HasBytesAvailable:
                var inputBuffer = Array<UInt8>(count:2048, repeatedValue: 0)
                inputStream?.read(&inputBuffer, maxLength: 2048)
                TestViewController().setStopButtonState(String(bytes: inputBuffer, encoding: NSUTF8StringEncoding)!)
                break
            default:
                break
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

让套接字有回调,并在流有字节时调用它:

import UIKit

class TestViewController: UIViewController {

@IBOutlet weak var connectButton: UIBarButtonItem!
@IBOutlet weak var stopButton: UIBarButtonItem!

let socket = Socket()

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func connectServer(sender: UIBarButtonItem) {
    socket.connect("10.0.0.1", port: 12345)
    socket.changeWhenHasBytesAvailable = { str in
        // do change for the string
    }
}

func setStopButtonState(state: String) {
    switch state {
    case "go":
        stopButton?.title = "STOP"
        break
    case "stop":
        stopButton?.title = "Start"
        break
    default:
        break
    }
}
}

class Socket: NSObject, NSStreamDelegate {
var inputStream: NSInputStream?
var outputStream: NSOutputStream?
var changeWhenHasBytesAvailable: ((String)->())?

func connect(host: String, port: Int) {
    NSStream.getStreamsToHostWithName(host, port: port, inputStream: &inputStream, outputStream: &outputStream)
    if inputStream != nil && outputStream != nil {
        inputStream!.delegate = self
        outputStream!.delegate = self
        inputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        outputStream!.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        inputStream!.open()
        outputStream!.open()
    }
}

func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
    if aStream === inputStream {
        switch eventCode {
        case NSStreamEvent.HasBytesAvailable:
            var inputBuffer = Array<UInt8>(count:2048, repeatedValue: 0)
            inputStream?.read(&inputBuffer, maxLength: 2048)
            //call it in main queue
            dispatch_async(dispatch_get_main_queue(), { 
                self.changeWhenHasBytesAvailable?(String(bytes: inputBuffer, encoding: NSUTF8StringEncoding)!)
            })
            break
        default:
            break
        }
    }
}
}