无法在Swift中写入NSOutput Stream

时间:2016-01-18 15:16:48

标签: ios iphone swift external-accessory nsoutputstream

自上周以来,我正在使用Swift开发一个App。这是我第一次使用swift,现在我第一次使用swift。 我必须使用ExternalAccessory框架,因为我想连接到设备并将数据写入NSOutput流。 一旦我尝试将数据写入流,我的应用程序就崩溃了。因为我必须使用闪电端口作为我的外部设备,所以我不能使用xCode的任何调试功能。因为我没有坚持,我真的很感谢你的帮助...... 以下是我的代码的相关部分:

def create(self, validated_data):

    if 'recipients' in validated_data:
        recipients_data = validated_data.pop('recipients')
    else:
        recipients_data = []

    for recipient_data in recipients_data:
        created_my_model = MyModel.objects.create(recipient=User.objects.get(id=recipient_data['id']),
                                                  text=validated_data['text'])

    return something # here you need to decide what to return

}

这是错误日志:

import UIKit
import ExternalAccessory

class ViewController: UIViewController, NSStreamDelegate {
@IBOutlet weak var nameLabel: UILabel!
private var inStream: NSInputStream?
private var outStream: NSOutputStream?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: Actions
@IBAction func connectToHardware(sender: UIButton) {
    var man: EAAccessoryManager
    man = EAAccessoryManager.sharedAccessoryManager()
    let accs = man.connectedAccessories

    if (accs.count == 1){
        if let acc = accs.first {
            showDeviceData(acc)
            // ry to connect...
            connectToDevice(acc)

        }else{
            showAlert("Device is nil")
        }
    }else{
        showAlert("0 or too many devices connected...")
    }
}

func connectToDevice(device: EAAccessory){
    let prots = device.protocolStrings
    if prots.count == 1 {
        let session = EASession.init(accessory: device, forProtocol: prots.first!)
        self.outStream = session.outputStream
        self.inStream = session.inputStream

        if self.outStream != nil && self.inStream != nil {
            self.outStream?.delegate = self
            self.outStream?.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            self.outStream?.open()
            self.inStream?.delegate = self
            self.inStream?.scheduleInRunLoop(.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            self.inStream?.open()
            // TODO: at some point we have to close the streams...
        }else {
            showAlert("At least one of the streams is nil...")
        }
    }else {
        showAlert("The device has 0 or to many protocols...")
    }
}

final func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
    switch eventCode {
    case NSStreamEvent.EndEncountered:
        showAlert("Delegate: EndEncountered")
        break;

    case NSStreamEvent.ErrorOccurred:
        showAlert("Delegate: ErrorOccurred: \(aStream.streamError?.description)")
        break;

    case NSStreamEvent.OpenCompleted:
        showAlert("Delegate: OpenCompleted")
        break;

    case NSStreamEvent.HasBytesAvailable:
        showAlert("Delegate: HasBytesAvailabel")
        break;

    case NSStreamEvent.HasSpaceAvailable:
        showAlert("Delegate: HasSpaceAvailabel")

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
            if let test = aStream as? NSOutputStream {
                let res = test.write([0], maxLength: 1)
                self.showAlert(String(res) + " Bytes written")
            }else{
                self.showAlert("No OutputStream...")
            }
        })

        break;

    default:
        showAlert("Delegate: Default")
        break;
    }
}

func showDeviceData(device: EAAccessory){
    var msg = "Manufacturer: "
        + device.manufacturer
        + " Name: "
        + device.name
        + " Model number: "
        + device.modelNumber
        + " Serial number: "
        + device.serialNumber
        + " Firmware revision: "
        + device.firmwareRevision
        + " Hardware revision: "
        + device.hardwareRevision
        + " Protocol strings: "

    let prots = device.protocolStrings

    for item in prots{
        msg += " " + item
    }

    showAlert(msg)
}

func showAlert(message: String){
    let alert = UIAlertView()
    alert.title = "Message..."
    alert.message = message
    alert.addButtonWithTitle("OK")
    alert.show()
}

如果我尝试在没有dispatch_async方法的情况下写入流,应用程序会冻结,我不会收到错误日志。

请询问您是否需要任何进一步的信息。

0 个答案:

没有答案