문제

I'm trying to connect to a Node.JS server with an iOS App, but instead of using a 3rd party native library, I'm trying to connect it with the JavaScript Socket.IO client & to pass the data that I'm receiving to my native code. I'm loading the Socket.IO module into the JSContext & it loads well, I can see all the available objects/functions inside the io object.

But when it reaches the line for connecting to my Node.JS server the execution of my JavaScript code stopes & I cannot find out why.

If I pause the app I don't see any additional threads for opening connections. Is it possible that JavaScriptCore doesn't have support for web sockets?

My Objective-C code:

JSContext *context = [JSContext new];

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"socket.io" ofType:@"js"];
NSString *socketIO = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];;


filePath = [[NSBundle mainBundle] pathForResource:@"client" ofType:@"js"];
NSString *client = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
context[@"socket_url"] = @"http://192.168.1.128:8080";
context[@"log"] = ^(NSString *string){

    NSLog(@"JavaScript:\n\t%@", string);
};
context[@"iOSBlock"] = ^(id deviceState) {

    id JSON = [NSJSONSerialization JSONObjectWithData:deviceState options:NSJSONReadingMutableLeaves error:nil];
    // I'll do something here if I get reach this part :)
};

[context evaluateScript:socketIO];
[context evaluateScript:client];

My JavaScript code:

var socket = io.connect(socket_url);

socket.on('connect', function(){
      log("Connected!");
});

socket.on('device-change', iOSBlock(deviceState)); 
도움이 되었습니까?

해결책

JavaScriptCore itself only implements the ECMAScript spec. Stuff like XMLHTTPRequest, web sockets, DOM, etc. comes from WebKit. If you absolutely want to run the Socket.IO JavaScript client, you can perhaps use a hidden UIWebView, although I'd recommend using Socket.IO-objc.

On an unrelated note, you can see what errors JSContext generates by either inspecting its exception property, or by setting a block that prints the error to the exceptionHandler property:

context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
    NSLog(@"[%@:%@:%@] %@\n%@", exception[@"sourceURL"], exception[@"line"], exception[@"column"], exception, [exception[@"stack"] toObject]);
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top