我的代码在另一个项目中的类中具有以下签名:

class ViewController: UIViewController, NSStreamDelegate, UITextFieldDelegate  {

然后我将连接移到它自己的类中,因此我可以在每个连接中重用它:
class XMPPConnection: NSObject, NSStreamDelegate

完成此操作后,我将所有viewDidLoad()代码移到init()中。我还尝试将init代码放在单独的函数中,并在实例化该类后调用该函数。那并没有改变任何东西。

我可以在两个项目之间进行切换,以确保这不是服务器问题,并确认这不是服务器问题。

每次运行该应用程序后,结果都是不同的。它要么不调用HasSpaceAvailable而仅坐在那里,要么在我的类(lldb)中的线程1上抛出class AppDelegate: UIResponder, UIApplicationDelegate, FBLoginViewDelegate错误。该错误可能与Facebook集成有关,但是lldb没什么可看的。但是,与其他项目不同,每次运行时都不会调用HasSpaceAvailable

这是NSStreamDelegate的完整代码,因此没有混淆。此类是使用XMPP协议(protocol)的相当标准的连接方法。
import UIKit
import Foundation


class XMPPConnection: NSObject, NSStreamDelegate { //NSObject

    var input : NSInputStream?
    var output: NSOutputStream?

    //let XMLStream: String = "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' version='1.0' xmlns='jabber:client' to='mydomain.com' xml:lang='en' xmlns:xml='http://www.w3.org/XML/1998/namespace'>"
    let XMLStream: String = "<stream:stream to='mydomain.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>"
    var XMLAuth: String?
    let XMLStreamEnd: String = "</stream:stream>"
    let XMLResource: String = "<iq type='set' id='bind_1'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>OneSide</resource></bind></iq>"
    let XMLSession: String = "<iq type='set' id='sess_1'><session xmlns='urn:ietf:params:xml:ns:xmpp-session'/></iq>"
    let XMLStartTLS: String = "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>";
    var messagesToBeSent:[String] = []
    var lastSentMessageID = 0
    var lastReceivedMessageID = 0


    init(facebookID: String) {
        super.init()
        let username = "[email protected]" //should hash device ID
        let password = "123456" //hash it
        var UTF8AuthStr = "\0\(username)\0\(password)".dataUsingEncoding(NSUTF8StringEncoding)
        let Base64Str = UTF8AuthStr!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
        XMLAuth = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>\(Base64Str)</auth>"
        //println(XMLAuth)

        self.connectToSocket("mydomain.com", port: 5222)
        send(self.XMLStream)
        //send(self.XMLStartTLS)
        /*send(self.XMLAuth!)
        send(self.XMLStream)
        send(self.XMLResource)
        send(self.XMLSession)*/
        //sendMessage("hi")


    }

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

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

        self.input!.delegate  = self
        self.output!.delegate = self

        self.input!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
        self.output!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

        self.input!.open()
        self.output!.open()

        println("Connected")


        //let bytesWritten = self.output!.write(UnsafePointer(data.bytes), maxLength: data.length)

        //println(bytesWritten)


    }

    //The delegate receives this message when a given event has occurred on a given stream.
    func stream(theStream: NSStream!, handleEvent streamEvent: NSStreamEvent) {

        println("Message received")

        switch streamEvent {
        case NSStreamEvent.None:
            println("NSStreamEvent.None")
        case NSStreamEvent.OpenCompleted:
            println("NSStreamEvent.OpenCompleted")
        case NSStreamEvent.HasBytesAvailable:
            println("NSStreamEvent.HasBytesAvailable")
            if let inputStream = theStream as? NSInputStream {
                //println("is NSInputStream")
                if inputStream.hasBytesAvailable {
                    //println("hasBytesAvailable")
                    let bufferSize = 1024
                    var buffer = Array<UInt8>(count: bufferSize, repeatedValue: 0)

                    var bytesRead: Int = inputStream.read(&buffer, maxLength: bufferSize)
                    //println(bytesRead)
                    if bytesRead >= 0 {
                        lastReceivedMessageID++
                        var output: String = NSString(bytes: &buffer, length: bytesRead, encoding: NSUTF8StringEncoding)
                        //println("output is")
                        println(output)
                    } else {
                        println("error")
                        // Handle error
                    }
                }
            }
        case NSStreamEvent.HasSpaceAvailable:
            println("NSStreamEvent.HasSpaceAvailable")
            send(nil) //send next item
            //send next message or
            //what if there is no next message to send, and instead waiting user input?
        case NSStreamEvent.ErrorOccurred:
            println("NSStreamEvent.ErrorOccurred")
        case NSStreamEvent.EndEncountered:
            println("NSStreamEvent.EndEncountered")
        default:
            println("default")
        }
    }

    func send(message:String?){
        if (self.output!.hasSpaceAvailable){ //stream ready for input
            //println("true hasSpaceAvailable")
            var data:NSData
            var thisMessage:String
            if message == nil{ // no message specified
                if messagesToBeSent.count != 0{ //messages waiting to be sent
                    thisMessage = messagesToBeSent[0]
                    data = messagesToBeSent[0].dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
                    messagesToBeSent.removeAtIndex(0)
                }
                else{ //no data to be sent
                    //no message specified and nothing to be sent
                    return
                }
            }
            else{
                thisMessage = message!
                data = message!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
            }

            //println("Sent the following")
            wait()
            let bytesWritten = self.output!.write(UnsafePointer(data.bytes), maxLength: data.length)
            lastSentMessageID++
            //println(thisMessage)
            //println("Message sent to server and response is")
            //println(bytesWritten) //int count
        }
        else{ //steam busy
            println("no space available in stream")
            if message != nil{
                messagesToBeSent.append(message!)
            }
        }
    }

    func sendMessage(message:String, from:String, to:String){
        let xmlMessage = "<message to='\(to)@mydomain.com' from='\(from)@mydomain.com' type='chat' xml:lang='en'> <body>\(message)</body></message>"
        send(xmlMessage)
    }


    func wait() {
        while true {
            //println("waiting")
            if lastSentMessageID == lastReceivedMessageID {
                break
            }

            NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.1));
            NSThread.sleepForTimeInterval(0.1)
        }
    }

}

因此,我看到了可能导致此问题的两件事。要么将其移入其自己的类并为其创建实例,要么更改继承。考虑到第一个可能性,我正在研究代码的线程行:self.input!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
检查streamStatus.toRaw()后,它说1就是NSStreamStatusOpening。我不确定这种情况是否会改变。

最佳答案

如果XMPPConnection存储在本地变量中,我可以重现该问题,
例如

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let conn = XMPPConnection(facebookID: "...")
    return true
}

该方法返回时,实例将被释放。另一方面,流
代表仍然指向实例,这会导致崩溃。 delegateNSStream的属性声明为
unowned(unsafe) var delegate: NSStreamDelegate?

这是Swift的“assign”(也称为“unsafe_unretained”)的等效项。因此
设置委托(delegate)不保留对象,并取消分配对象
不会将该属性设置为nil(对于弱引用)。

如果实例存储在属性中,例如
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var conn : XMPPConnection!

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        conn = XMPPConnection(facebookID: "...")
        return true
    }

    // ...
}

那么您的代码在我的测试中可以正常工作。

07-25 21:32