A conforming Objective-C WebSocket client library.

Sending a UILocationNotification from the background

I have an app where I need to send a UILocationNotification when the app is not in the foreground / Active. If I have my code to do so, it will not send until the app is opened and is active.

Here is my function:

- (void)setLocalNotificationForType:(SPKLocalNotificationType)notificationType fromUser:(NSString *)userName withMessageText:(NSString *)msgText {

    UILocalNotification *notif = [[UILocalNotification alloc] init];
    notif.userInfo = @{@"handle": _convoHandle, @"room": _convoName};
    notif.fireDate = [NSDate date];
    notif.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
    notif.soundName = UILocalNotificationDefaultSoundName;
    notif.timeZone = [NSTimeZone defaultTimeZone];

    if (notificationType == 1) { // message
        notif.alertBody = [NSString stringWithFormat:@"@%@ said: \"%@\"", userName, msgText];
    } else if (notificationType == 2) { // image
        notif.alertBody = [NSString stringWithFormat:@"@%@ sent an image", userName];
    } else {

    if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive) {
        [[UIApplication sharedApplication] presentLocalNotificationNow:notif];

Update: It now seems that the problem is that the connection to the server is being "paused" while the app is in the background. Once I then open the app all the data comes in at once. I am using SocketRocket for connecting to my Node.js Primus web socket server. Is this something that normally happens? This is my first time using SocketRocket so I'm not sure.

Update: I have also enabled Remote Notifications for Background Modes, I have also registered for remote notifications, and on the device, I have also made sure that "banners" and "badges" are enabled.

Update: I have additionally set the web socket to use a background queue.

[webSocket setDelegateOperationQueue:[NSOperationQueue new]];

The connection is still being paused.


Source: (StackOverflow)

Why does my websocket server always report [websocket: control frame length > 125]?

My iOS application uses SocketRocket to establish a connection with my websocket server. But after establishing a connection and sending the first message, the server (using gorilla/websocket) tries to parse the frame, but failed:

message_type, r, err := ws.NextReader()
if err != nil {
    goto end

An error is reported when calling NextReader():

Websocket Read Failed: [websocket: control frame length > 125]

The strange thing is, I use SocketRocket's send() method to send data, so there should never be any control frames (ping/pong).

Has anyone seen this problem before? Help!

Source: (StackOverflow)

Implementin SRWebSocketDelegate in Swift

I am implementing:

@protocol SRWebSocketDelegate <NSObject>

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message;


- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;

in Swift. All functions I can implement ok and works, but didCloseWithCode I just can't make it to work.

I am having trouble implementing

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;

in Swift.

I am trying:

func webSocket(webSocket: SRWebSocket!, didCloseWithCode code: NSInteger!, reason: NSString!, wasClean: Bool!) {
    println("websocket closed: \(reason)")

with no luck.

Source: (StackOverflow)

Web Socket: cannot detect client connection on internet disconnect

I want to detect the client connection if client turn off the internet using web socket. My code is:

 //Include util library
    var util = require('util');
    // Include underscore library
    var _ = require('underscore')._;
    //For websocket
var webSocketServer = new (require('ws')).Server({port: (process.env.PORT || 5000)}),
webSockets = {} // userID: webSocket

// CONNECT /:userID
// wscat -c ws://localhost:5000/1
webSocketServer.on('connection', function (webSocket) 
  var userID = webSocket.upgradeReq.url.substr(1);
  //console.log('User_id is ',userID);
  webSockets[userID] = webSocket
                   util.log('User_id: [' + userID + '] enter in connected users list of [ ' + Object.getOwnPropertyNames(webSockets)+' ]')
                   // Call function which check id exist in letswalkee DB table

                   // Send msg like: [fromUserID, text]    [1, "Hello, World!"]
webSocket.on('message', function(message) {
util.log('Received from [' + userID + ']: ' + message)
var messageArray = JSON.parse(message)
                                    var toUserWebSocket = webSockets[messageArray[0]]
                                    if (toUserWebSocket) {
                                    util.log('Sent to [' + messageArray[0] + ']: ' + JSON.stringify(messageArray))
                                    messageArray[0] = userID

                   webSocket.on('close', function () 
                      delete webSockets[userID]
                      util.log('User_id Deleted from connected users: [ ' + userID+' ]');

   console.log('hello i am disconnected');  

I used that code (webSocket.on('disconnect',function()) but did not worked? Help asap?

Source: (StackOverflow)

Calling a delegate function and return result

Im doing a small test project with SocketRocket on ios. But i can't seem to wrap my head around the logic.

Here's the thing: I have need to have a sort of "global" function to call the sockets. When my app opens it should connect using the websockets.

_webSocket.delegate = nil;
[_webSocket close];

_webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://localhost:12345/connectr"]]];
_webSocket.delegate = self;

self.title = @"Opening Connection...";
[_webSocket open];

However, i need to get the logic on connecting to a delegate function. I already thought of a singleton but i read that the singleton functions are quite cpu expensive.

So basically my question is: What is the best way to initiate a global accesable function that uses the (appdelegate) initalized SocketRocket instance.

Source: (StackOverflow)


I'm getting iOS EXC_BAD_ACCESS errors while using SocketRocket, and I wonder what I can do to further debug the issue to determine if the problem is on my side, or on SocketRocket's side.

The stacktrace I get is :

0    libobjc.A.dylib     objc_msgSend + 5
1    OMlearnings         SRWebSocket.m line 692    __30-[SRWebSocket _failWithError:]_block_invoke_2
2    libdispatch.dylib   _dispatch_call_block_and_release + 10
10   UIKit               UIApplicationMain + 1136
11   OMlearnings         main.m line 16    main

or sometimes

Crashed: NSOperationQueue Serial Queue
0    libobjc.A.dylib     objc_msgSend + 5
1    OMlearnings         SRWebSocket.m line 613    -[SRWebSocket scheduleInRunLoop:forMode:]
2    OMlearnings         SRWebSocket.m line 600    -[SRWebSocket _connect]
3    OMlearnings         OMSRealTimeTeamDashboard.m line 157    -[OMSRealTimeTeamDashboard sendMessage:]
4    OMlearnings         OMSRealTimeTeamDashboard.m line 171    -[OMSRealTimeTeamDashboard eventReceived:]
5    CoreFoundation      __invoking___ + 68
6    CoreFoundation      -[NSInvocation invoke] + 282
7    Foundation          -[NSInvocationOperation main] + 112
8    Foundation          -[__NSOperationInternal _start:] + 770
14   libsystem_pthread.dylib _pthread_wqthread + 298

My codebase is quite simple and basically subscribes to events, and executes socketrocket sendMessage in a queue (to deal with concurrency)

[signalServices subscribe:my-event toBlock:^(NSNotification * notification) {
    [this.queue addOperation:[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(eventReceived:) object:notification]];

- (void)eventReceived: (NSNotification *)notification {
    // ...
    [socket send:[NSString stringWithFormat:@"%i,1,%@", currentUserId.intValue, [NSNumber numberWithInt: rate.value]]];

I've read people using NSZombies to debug the issue, but my problem only happens rarely, so I would likely run out of memory before the problem becomes visible. It works fine 99% of the time.

Is there anything to know about iOS that could randomly crash apps that use sockets, etc ? For instance, we have background fetch enabled, could that be the cause of some of the random crashes ?

Thanks !

Source: (StackOverflow)

SocketRocket RunLoop sporadic crash

So our app has been experiencing crashes for a while in SocketRocket. We get about 20 crashes a day from it, with the following stack trace:


Thread : Crashed:
0  libsystem_platform.dylib       0x3b8ff816 spin_lock$VARIANT$mp + 1
1  CoreFoundation                 0x30e2d593 CFSocketEnableCallBacks + 54
2  CFNetwork                      0x30a926f9 SocketStream::securityBufferedRead_NoLock() + 212
3  CFNetwork                      0x30a925f5 SocketStream::socketCallbackReadLocked(SocketStreamSignalHolder*) + 76
4  CFNetwork                      0x30a90d8f SocketStream::socketCallback(__CFSocket*, unsigned long, __CFData const*, void const*) + 102
5  CFNetwork                      0x30a90cf3 SocketStream::_SocketCallBack_stream(__CFSocket*, unsigned long, __CFData const*, void const*, void*) + 58
6  CoreFoundation                 0x30e6a337 __CFSocketPerformV0 + 578
7  CoreFoundation                 0x30e68183 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 14
8  CoreFoundation                 0x30e67653 __CFRunLoopDoSources0 + 206
9  CoreFoundation                 0x30e65e47 __CFRunLoopRun + 622
10 CoreFoundation                 0x30dd0c27 CFRunLoopRunSpecific + 522
11 CoreFoundation                 0x30dd0a0b CFRunLoopRunInMode + 106
12 Foundation                     0x317be3db -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 254
13 Piazza                         0x00110b7b -[_SRRunLoopThread main]
14 Foundation                     0x31880c87 __NSThread__main__ + 1062
15 libsystem_pthread.dylib        0x3b904c1d _pthread_body + 140
16 libsystem_pthread.dylib        0x3b904b8f _pthread_start + 102

I've been trying to nail it down for over 20 hours. It's pretty sporadic - the best way I have of reproducing it is to log out, so the connections all fail, and then try to incite some connections, and/or wait for several minutes. Works about 1/4 of the time, after a few minutes. However, there are logs of people experiencing this crash while still logged in.

As far as the code, I can't tell what is causing the EXC_BAD_ACCESS, since all the entries above 13 have no available source, and looking at the assembly code hasn't really enlightened me much - all I've discovered is that ecx gets set to 0xc in the course of things, and then spin_lock$VARIANT$mp tries to swap some register for stuff located at ($ecx), and it crashes. [_SRRunLoopThread main], the only part of the stack trace I have source for, is as follows:

- (void)main;
    @autoreleasepool {
        _runLoop = [NSRunLoop currentRunLoop];

        NSTimer *timer = [[NSTimer alloc] initWithFireDate:[NSDate distantFuture] interval:0.0 target:nil selector:nil userInfo:nil repeats:NO];
        [_runLoop addTimer:timer forMode:NSDefaultRunLoopMode];

        int i = 0;

        while ([_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {

It crashes on the while line. I suspect that something, somewhere, is getting deallocated before it's supposed to, but I'm not sure if it's an SRWebSocket or somehow a block that was added to the run loop or what. I'm not totally familiar with run loops.

I'm running out of productive things to do to figure this out, and I've made barely any progress. Any help is appreciated.

Source: (StackOverflow)

SocketRocket and iOS certificate pinning

I'm currently using SocketRocket as the WebSocket implementation for my iOS applications and would like to pin my server's CA as a trusted certificate with the SR_SSLPinnedCertificates property. I'm looking for a good example of loading one or more certificates to pass into SocketRocket. I've got the following code to work but I'm not sure it's correct or if there is a more straight-forward approach.

CFArrayRef keyref = NULL;
NSString *path = [[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"p12"];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
OSStatus status = SecPKCS12Import((__bridge CFDataRef)data, (__bridge CFDictionaryRef)[NSDictionary dictionaryWithObject:@"eftl_key_pass" forKey:(__bridge id)kSecImportExportPassphrase], &keyref);
if (status == noErr) {
    CFDictionaryRef identityDict = CFArrayGetValueAtIndex(keyref, 0);
    SecIdentityRef identityRef = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
    SecCertificateRef certRef = NULL;
    SecIdentityCopyCertificate(identityRef, &certRef);

Source: (StackOverflow)

SocketRocket connection pausing while in background

I am using SocketRocket, but I cannot get it to deliver messages while in the background. When I open the app again, it resumes the connection (without reconnecting) and the messages all come in at once.

Here is my connection code:

- (void)_reconnect {
    _websocket.delegate = nil;
    [_websocket close];

    NSString *host = @"ws://localhost:3030/primus";

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:host]];
    [request setValue:[NSString stringWithFormat:@"<%@>", apiKey] forHTTPHeaderField:@"Authentication"];

    _websocket = [[SRWebSocket alloc] initWithURLRequest:request];
    [_websocket setDelegateOperationQueue:[NSOperationQueue new]];
    _websocket.delegate = self;

    [_websocket open];

    if (DEBUG) {
        NSLog(@"Using: %@", host);

I have also tried without the

[_websocket setDelegateOperationQueue:[NSOperationQueue new]];

line, but that doesn't help anything.

Do you have any idea what's going on?


Source: (StackOverflow)

How to create a CocoaPod with nested git submodules?

I'm trying to create a CocoaPod with nested git submodules. I can create the pod, however, I can't fully install it.

When I run pod install --verbose I can see that git submodule update --init is being run instead of git submodule update --init --recursive which doesn't pull the nested submodule.

Does CocoaPods support nested submodules, or no? I have scoured the web for potential leads, but can't find anything!

I should also mention that I that lint passes with pod lib lint but not pod spec lint. pod spec lint complains that it can't find the header file in the nested submodule. I'm not sure if this is related to the problem above.

(Also note that this particular Pod I'm working on is only a proof of concept. I'll be creating a much more complex Pod that depends on socket.IO-objc. Unfortunately socket.IO-objc is not available as a Pod, and depends on SocketRocket as a submodule.)

Here's my PodSpec: do |s|             = "DebugTools"
  s.version          = "0.1.0"
  s.summary          = "Awesome tools for debugging iOS apps."
  s.homepage         = ""
  s.license          = 'MIT'           = { "Robert Crabtree" => "" }
  s.source           = { :git => "", :tag => s.version.to_s, :submodules => true }

  s.platform     = :ios, '7.0'
  s.requires_arc = true

  s.source_files = 'Pod/Classes/**/*', 'Pod/Submodules/LogMaster/LogMaster/*.{h,m}', 'Pod/Submodules/LogMaster/LogMaster/LogCore/*.h'
  s.resource_bundles = {
    'DebugTools' => ['Pod/Assets/*.png']

Here's my Podfile:

pod "DebugTools", :git => "", :submodules => true

Source: (StackOverflow)

iOS Client connecting to NodeJS results in Stream end encountered

I have a NodeJS server that uses and listen to port 8000. The code is something like this:

var io = require("");
var socket = io.listen(8000);
socket.sockets.on("connection", function(client) {
    util.log("Client connects: " +;

I have written a web client that can connects to this server and it works just fine. So the server code is not the problem. The problem is with the iOS client that I am about to describe next.

The iOS client uses SocketRocket and to install it, I use Cocoapods and have a Podfile with the following:

platform :ios
pod 'SocketRocket', '0.2.0'

In MyViewController.h

#import <SocketRocket/SRWebSocket.h>

@interface MyViewController : UIViewController<SRWebSocketDelegate> 
    @property (strong, nonatomic) SRWebSocket *socket;

In MyViewController.m

@synthesize socket = _socket;

- (void)viewDidLoad
    _socket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
    _socket.delegate = self;

    [_socket open];


- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    NSLog(@"Error didReceiveMessage");

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    NSLog(@"Error connecting websocket");

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    NSLog(@"Error didCloseWithCode %d: %@", code, reason);

When the iOS client runs, the log "Connect" shows up. But the delegate didCloseWithCode() also gets invoked. And the log shows

Error didCloseWithCode 0: Stream end encountered

I have spent lots of time trying to figure out, but it's time to get some help from experts. Why am I getting the "Stream end" problem. The NodeJS server is working just fine, since I can connect to it with a web client. What am I doing wrong with the iOS client and how can I correct?

Update: Add JavaScript code on the server to show the util.log() call. When the web client connects, console shows "Client connects"..." message. When the iOS client attempts to connect, nothing on the console.

Source: (StackOverflow)

.framework product is red no matter what

I'm trying to add this framework to a project. I have followed these instructions to the letter:

  1. Add SocketRocket.xcodeproj as either a subproject of your app or in your workspace.
  2. Add SocketRocket.framework to the link libraries
  3. If you don't have a "copy files" step for Framework, create one
  4. Add SocketRocket.framework to the "copy files" step.

I made sure I had only one instance of xcode open, then dragged the SocketRocket.xcodeproj file into my project. I added the .framework file to the link libraries, created a copy files build phase, then added the .framework to the copy files build phase.

This is the error I get when I try to build:

clang: error: no such file or directory: '/Users/adamhickey/Library/Developer/Xcode/DerivedData/websockettest-fcuhfltporfkitgubwcjukxogzas/Build/Products/Debug-iphonesimulator/SocketRocket/SocketRocket'

It's quite right: that directory does not exist.

In build phases, the SocketRocket.framework is red under Link Binary With Libraries. It's also red in the products folder of the SocketRocket subproject.

I've been googling this error for hours and the majority of the things I've tried have pointed me towards changing the build location in Xcode->preferences-locations. I've tried:

  1. setting it to relative, picking my own, and going to advanced and choosing legacy.
  2. building for a device
  3. build for->archiving
  4. building for release

If I open the SocketRocket.xcodeproj in a separate instance of xcode and try to build it, 3 of the four products are red. The products are: libSocketRocket.a, SRWebSocketTests.octest,, and SocketRocket.framework. The first is white, while the last three are red.

I'm assuming that if I can get the .framework file to build in a separate project, this will solve my overall problem. However, nothing I do seems to have any effect.

Please please please help! I'm using xcode 4.6.

Source: (StackOverflow)

Error in opening .xcworkspace

I integrated pods in my project specifically SignalR, AFNetworking and SocketRocket. It was successfully installed, but when I opened .xcworkspace, this error shows:

enter image description here

This is what the project navigator looks like

Has anyone encountered this kind of error? Thanks in advance.

Update: My .xcodeproj has appeared. But the frameworks appear red. How can I solve this?

enter image description here

Source: (StackOverflow)

Class is implemented in both. One of the two will be used

I have a project that has a dependency (installed via CocoaPods) using SocketRocket and have imported a static library from HeapAnalytics. Apparently the HeapAnalytics library already uses SocketRocket. I get no errors when compiling, but at runtime receive the following:

Class SRWebSocket is implemented in both [path] and [path].
One of the two will be used. Which one is undefined.

I'm not sure how to handle it because most solutions I've seen require compiling the static library yourself change class names and such, and I don't have access to the source.

Any recommendations?

Source: (StackOverflow)

iOS Client connecting to server using socketrocket results in "Stream end encountered"

NSString *urlString = @"ip address";
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
self.webSocket.delegate = self;
[self.webSocket open];

Here didCloseWithCode is called with reason Stream end encountered.

Any ideas about what might go wrong?

Source: (StackOverflow)