编组目标c到nativescript js

时间:2016-09-03 12:02:51

标签: nativescript

您好我正在尝试使用以下cocoa pod来实现ios中的tcp功能: https://cocoapods.org/pods/CocoaAsyncSocket

我正面临使用此库编写编组js的问题

这是一个例子(目标C):

// The most common way to initialize an instance is simply like this:
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

NSError *err = nil;
if (![socket connectToHost:@"deusty.com" onPort:80 error:&err]) // Asynchronous!
{
    // If there was an error, it's likely something like "already connected" or "no delegate set"
    NSLog(@"I goofed: %@", err);
}
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"Cool, I'm connected! That was easy.");
} 

JSCODE:

// mainQueue var is to get dispatch_get_main_queue
var mainQueue = (function() {
    var runloop = CFRunLoopGetMain();
    return function(func) {
        CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, func);
        CFRunLoopWakeUp(runloop);
    }
}());

var tcpClient = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(testerClass,mainQueue);
var e = new interop.Reference();
if (!tcpClient.connectToHostOnPortError('192.168.88.110',3333,e)) {
    console.log('Could not connect to mipbook');
    console.log(e.value);
}
function socketDidConnectToHost(sock,host,port) {
    console.log('connected to host');
}

connect to port部分工作正常,但是在连接成功时没有调用委托实例方法。

2 个答案:

答案 0 :(得分:0)

好的,我得到了它的工作 问题在于编组dispatch_get_main_queue()。我通过在所使用的pod的源代码中编辑GDCAsyncSocket.m来使我的脚本工作。

GDCAsyncSocket.m:

delegateQueue = dq;

更改为

delegateQueue = dispatch_get_main_queue();

这样就不再需要从js端传递dispatch_get_main_queue(),它的值在目标c库中计算。

以下是正在使用的JS代码:

var tcpClientDelegate = NSObject.extend({
    socketDidConnectToHostPort(sock,host,port) {
        console.log('connected to host: '+host);
        console.log('connected to port: '+port);
    }
}, {
    protocols: [GCDAsyncSocketDelegate]
});

var clientInstance = new tcpClientDelegate();
var tcpClient = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(clientInstance,null);
var e = new interop.Reference();
if (!tcpClient.connectToHostOnPortError('192.168.88.110',3333,e)) {
    console.log('Could not connect to mipbook');
    console.log(e.value);
}

答案 1 :(得分:0)

尝试过:

let delegate = ...
let dispatchQueue = dispatch_queue_create("test_queue", null);
let udp = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(delegate, dispatchQueue);

它工作正常。也应为GCDAsyncSocket工作。 出于某种原因,未定义dispatch_get_main_queue()。