Не удается записать поток NSOutput в Swift
С прошлой недели я занимаюсь разработкой приложения с использованием Swift. Я впервые работаю со Swift, и теперь я борюсь впервые. Я должен использовать платформу ExternalAccessory и для этого я хочу подключиться к устройству и записать данные в поток NSOutput. Как только я пытаюсь записать данные в поток, мое приложение вылетает. И так как я должен использовать порт молнии для моего внешнего устройства, я не могу использовать какие-либо функции отладки xCode. Из-за этого я застрял нет, и я был бы очень признателен за вашу помощь... Вот соответствующие части моего кода:
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()
}
}
А вот и журнал ошибок:
Incident Identifier: 9A93439A-CF19-4418-B413-6C75F91E4E16
CrashReporter Key: fc823ef3cdfaefaca2ed524c6fcc0fe82b5a0d33
Hardware Model: iPhone8,1
Process: Test Prototyp [4169]
Path: /private/var/mobile/Containers/Bundle/Application/0BFFBF57-75EA-4EDD-AE2E-B3995E979334/Test Prototyp.app/Test Prototyp
Identifier: de.test.Test-Prototyp
Version: 1 (1.0)
Code Type: ARM-64 (Native)
Parent Process: launchd [1]
Date/Time: 2016-01-18 15:55:46.46 +0100
Launch Time: 2016-01-18 15:55:33.33 +0100
OS Version: iOS 9.2 (13C75)
Report Version: 105
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Triggered by Thread: 0
Filtered syslog:
None found
Last Exception Backtrace:
0 CoreFoundation 0x1830b5900 __exceptionPreprocess + 124
1 libobjc.A.dylib 0x182723f80 objc_exception_throw + 56
2 CoreFoundation 0x1830b5334 __NSFastEnumerationMutationHandler + 132
3 UIKit 0x1886d4c30 +[_UIAlertControllerShimPresenter _addPresenter:] + 224
4 UIKit 0x1886d3b90 -[_UIAlertControllerShimPresenter _presentAlertControllerAnimated:completion:] + 100
5 UIKit 0x188220874 -[UIAlertView _showAnimated:] + 260
6 Test Prototyp 0x1000272b8 ViewController.showAlert(String) -> () (ViewController.swift:137)
7 Test Prototyp 0x100026550 ViewController.stream(NSStream, handleEvent : NSStreamEvent) -> () (ViewController.swift:89)
8 Test Prototyp 0x100026920 @objc ViewController.stream(NSStream, handleEvent : NSStreamEvent) -> () (ViewController.swift:0)
9 ExternalAccessory 0x18e12eb40 -[EAOutputStream _streamEventTrigger] + 420
10 CoreFoundation 0x183071628 __CFSocketPerformV0 + 1216
11 CoreFoundation 0x18306cefc __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
12 CoreFoundation 0x18306c990 __CFRunLoopDoSources0 + 540
13 CoreFoundation 0x18306a690 __CFRunLoopRun + 724
14 CoreFoundation 0x182f99680 CFRunLoopRunSpecific + 384
15 GraphicsServices 0x1844a8088 GSEventRunModal + 180
16 UIKit 0x187e10d90 UIApplicationMain + 204
17 Test Prototyp 0x100029ac4 main (AppDelegate.swift:11)
18 libdyld.dylib 0x182b3a8b8 start + 4
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x0000000182c58140 __pthread_kill + 8
1 libsystem_pthread.dylib 0x0000000182d20ef8 pthread_kill + 112
2 libsystem_c.dylib 0x0000000182bc9dac abort + 140
3 libc++abi.dylib 0x00000001826fd3f4 __cxa_bad_cast + 0
4 libc++abi.dylib 0x0000000182719e98 default_unexpected_handler() + 0
5 libobjc.A.dylib 0x0000000182724248 _objc_terminate() + 124
6 libc++abi.dylib 0x0000000182716f44 std::__terminate(void (*)()) + 16
7 libc++abi.dylib 0x0000000182716b10 __cxa_rethrow + 144
8 libobjc.A.dylib 0x0000000182724120 objc_exception_rethrow + 44
9 CoreFoundation 0x0000000182f99728 CFRunLoopRunSpecific + 552
10 GraphicsServices 0x00000001844a8088 GSEventRunModal + 180
11 UIKit 0x0000000187e10d90 UIApplicationMain + 204
12 Test Prototyp 0x0000000100029ac4 main (AppDelegate.swift:11)
13 libdyld.dylib 0x0000000182b3a8b8 start + 4
Thread 1 name: Dispatch queue: com.apple.libdispatch-manager
Thread 1:
0 libsystem_kernel.dylib 0x0000000182c594fc kevent_qos + 8
1 libdispatch.dylib 0x0000000182b1c94c _dispatch_mgr_invoke + 232
2 libdispatch.dylib 0x0000000182b0b7bc _dispatch_source_invoke + 0
Thread 2:
0 libsystem_kernel.dylib 0x0000000182c58b6c __workq_kernreturn + 8
1 libsystem_pthread.dylib 0x0000000182d1d530 _pthread_wqthread + 1284
2 libsystem_pthread.dylib 0x0000000182d1d020 start_wqthread + 4
Thread 3 name: Dispatch queue: com.apple.root.default-qos
Thread 3:
0 libobjc.A.dylib 0x0000000182722514 object_getClass + 40
1 CoreFoundation 0x000000018306e730 __CFTypeCollectionRetain + 104
2 CoreFoundation 0x0000000182f96574 _CFArrayReplaceValues + 352
3 CoreFoundation 0x0000000182f963c4 CFArrayAppendValue + 168
4 CoreFoundation 0x0000000182fb1088 _flattenPlist + 280
5 CoreFoundation 0x000000018303743c __CFBinaryPlistWriteOrPresize + 160
6 Foundation 0x00000001839f0c0c -[NSKeyedArchiver finishEncoding] + 588
7 BaseBoard 0x00000001845f1b30 _BSCreateDataFromObject + 420
8 BaseBoard 0x00000001845f1e30 -[NSObject(BaseBoard) bs_secureEncoded] + 16
9 BackBoardServices 0x00000001846333c0 BKSHIDSetKeyCommands + 72
10 UIKit 0x0000000188066f74 -[UIApplication _updateSerializableKeyCommandsForResponder:] + 532
11 UIKit 0x0000000187ea26bc -[UIViewController setChildModalViewController:] + 272
12 UIKit 0x0000000188123214 -[UIViewController _presentViewController:modalSourceViewController:presentationController:animationController:interactionController:completion:] + 640
13 UIKit 0x0000000188124f84 -[UIViewController _presentViewController:withAnimationController:completion:] + 4644
14 UIKit 0x00000001881279c0 -[UIViewController _performCoordinatedPresentOrDismiss:animated:] + 472
15 UIKit 0x0000000187ea1cec -[UIViewController presentViewController:animated:completion:] + 184
16 UIKit 0x00000001886d565c -[_UIAlertControllerShimPresenterWindow presentAlertController:animated:completionBlock:] + 512
17 UIKit 0x00000001886d3c10 -[_UIAlertControllerShimPresenter _presentAlertControllerAnimated:completion:] + 228
18 UIKit 0x0000000188220874 -[UIAlertView _showAnimated:] + 260
19 Test Prototyp 0x00000001000272b8 ViewController.showAlert(String) -> () (ViewController.swift:138)
20 Test Prototyp 0x00000001000289c4 ViewController.(stream(ViewController) -> (NSStream, handleEvent : NSStreamEvent) -> ()).(closure #1) (ViewController.swift:95)
21 Test Prototyp 0x0000000100028a60 thunk (ViewController.swift:0)
22 libdispatch.dylib 0x0000000182b09630 _dispatch_call_block_and_release + 24
23 libdispatch.dylib 0x0000000182b095f0 _dispatch_client_callout + 16
24 libdispatch.dylib 0x0000000182b17a88 _dispatch_root_queue_drain + 2140
25 libdispatch.dylib 0x0000000182b17224 _dispatch_worker_thread3 + 112
26 libsystem_pthread.dylib 0x0000000182d1d470 _pthread_wqthread + 1092
27 libsystem_pthread.dylib 0x0000000182d1d020 start_wqthread + 4
Thread 4:
0 libsystem_kernel.dylib 0x0000000182c58b6c __workq_kernreturn + 8
1 libsystem_pthread.dylib 0x0000000182d1d530 _pthread_wqthread + 1284
2 libsystem_pthread.dylib 0x0000000182d1d020 start_wqthread + 4
Thread 5 name: com.apple.CFSocket.private
Thread 5:
0 libsystem_kernel.dylib 0x0000000182c58368 __select + 8
1 CoreFoundation 0x0000000183073028 __CFSocketManager + 648
2 libsystem_pthread.dylib 0x0000000182d1fb28 _pthread_body + 156
3 libsystem_pthread.dylib 0x0000000182d1fa8c _pthread_body + 0
4 libsystem_pthread.dylib 0x0000000182d1d028 thread_start + 4
Thread 6:
0 libsystem_kernel.dylib 0x0000000182c58b6c __workq_kernreturn + 8
1 libsystem_pthread.dylib 0x0000000182d1d530 _pthread_wqthread + 1284
2 libsystem_pthread.dylib 0x0000000182d1d020 start_wqthread + 4
Thread 7:
0 libsystem_kernel.dylib 0x0000000182c58b6c __workq_kernreturn + 8
1 libsystem_pthread.dylib 0x0000000182d1d530 _pthread_wqthread + 1284
2 libsystem_pthread.dylib 0x0000000182d1d020 start_wqthread + 4
Thread 0 crashed with ARM Thread State (64-bit):
x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x0000000157b29197
x4: 0x000000018271ae02 x5: 0x000000016fddf4e0 x6: 0x000000000000006e x7: 0x0000000000000f80
x8: 0x0000000008000000 x9: 0x0000000004000000 x10: 0x0000000000000002 x11: 0x0000000000000010
x12: 0x0000000000000000 x13: 0x0000000000000002 x14: 0x0000000000000000 x15: 0x0000030000000300
x16: 0x0000000000000148 x17: 0x0000000000000000 x18: 0x0000000000000000 x19: 0x0000000000000006
x20: 0x00000001a1191000 x21: 0x000000016fddf4e0 x22: 0x000000015660b160 x23: 0x00000001a119cb68
x24: 0x0000000000000001 x25: 0x2d00c1e184f0d870 x26: 0x0000000156606b00 x27: 0x0000000000000000
x28: 0x0000000000000001 fp: 0x000000016fddf440 lr: 0x0000000182d20ef8
sp: 0x000000016fddf420 pc: 0x0000000182c58140 cpsr: 0x00000000
Если я пытаюсь записать в поток без метода dispatch_async, приложение зависает, и я не получаю журнал ошибок.
Пожалуйста, спросите, нужна ли вам дополнительная информация.