1

我正在尝试创建一个将与外部附件对话的自定义框架工作

public class AccessoryClass : NSObject, NSStreamDelegate {

        func getConnectedAccessoris() -> Array<EAAccessory>{
            let accessories : Array<EAAccessory> = EAAccessoryManager.sharedAccessoryManager().connectedAccessories
            return accessories
        }

    public func openAccessory() {
            let _accessories = getConnectedAccessoris()
            var _accessory: EAAccessory?
            for acsy in _accessories {
                if acsy.protocolStrings.contains(PROTOCOL_STRING) {
                    _accessory = acsy
                }
            }
            if _accessory != nil {
                _session = EASession(accessory: _accessory!, forProtocol: protocolString)
                if _session != nil {
                    _session?.inputStream?.delegate = self
                    _session?.inputStream?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
                    _session?.inputStream?.open()
                    _session?.outputStream?.delegate = self
                    _session?.outputStream?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
                    _session?.outputStream?.open()                    
                }
            }
        }


    func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
        switch (eventCode) {
        case NSStreamEvent.None:
            print("NSStream None")
            break
        case NSStreamEvent.OpenCompleted:
            print("Open Completed")
            break
        case NSStreamEvent.HasBytesAvailable:
            print("Has Bytes Available")
//            _readData()
            break
        case NSStreamEvent.HasSpaceAvailable:
            print("Hase space Available")
//            _writeData()
            break
        case NSStreamEvent.ErrorOccurred:
           print("Error occurred")
            break
        case NSStreamEvent.EndEncountered:
            print("End Encountered")
            break
        default:
            print("No stream event")
            break
        }
    }

}

我试过这样,streamDelegate 只会崩溃。没有此代码 _session?.inputStream?.delegate = self 它工作正常。

我怀疑是否可以在创建自定义框架时使用 ios 委托方法。如果不是,使用什么程序??

谢谢

4

1 回答 1

0

使用警卫,然后设置委托

guard let inputStream = session.inputStream else {
            return
        }

inputStream.delegate = self
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode:NSDefaultRunLoopMode)
inputStream.open()
于 2016-02-26T17:21:52.740 回答