How to use Signalr in iOS? - ios

I have planned to use SignalR for my iOS application and searched for several hours to find a better solution but unfortunately I was not able to find a better solution for it.
Some of them where suggesting SignalR-ObjC for using SignalR in iOS but while I tried a sample with it, there were lot of issues on using SignalR-ObjC.
I'm looking forward to hear some third party plugins which makes SignalR integration possible at iOS.
Kindly advice me on how to use signalr for iOS application.
Note: Just as an additional information I'm providing the errors that I have struggled with SignalR-ObjC. If the errors are fixable then I will go ahead using the SignalR-ObjC for now.
The issues are: None of my clients are not getting invoked by server method call but SRConnectionDidOpen was getting invoked everytime.
I have mentioned by code below, kindly review it and let me know if I had done anything wrong with my code as I'm a beginner to Objective C.
hub = [connection createHubProxy:#"myHub"];
[hub on:#"addMessage" perform:self selector:#selector(addMessage:)];
connection.started = ^{
NSLog(#"started");
};
connection.received = ^(NSString * data) {
NSLog(#"%#",data);
};
[connection setDelegate:self];
[connection start];
}
- (void)addMessage:(NSString *)message{ // Print the message when it comes in
NSLog(#"message");
}
- (void)SRConnectionDidOpen:(SRConnection *)connection
{
[hub on:#"addMessage" perform:self selector:#selector(addMessage:)];
}
Thanks in advance.

Related

STOMP Websocket sometimes doesn't response

I have a service using STOMP Websocket, I use WebsocketStompKit library
https://github.com/rguldener/WebsocketStompKit
NSURL *websocketUrl = [NSURL urlWithString:#"ws://xxx/websocket"];
STOMPClient *client = [[STOMPClient alloc] initWithURL:websocketUrl websocketHeaders:nil useHeartbeat:NO];
[self.client connectWithHeaders:nil completionHandler:^(STOMPFrame *connectedFrame, NSError *error) {
NSString *status = [Utils getStringIgnoreNull:connectedFrame.command];
if ([status isEqualToString:#"CONNECTED"]) {
NSLog(#"-------Connected to socket server!");
[self subscribe];
}
}];
I followed the instructions to setup STOMPClient, it works ok.
But sometime, it doesn't run to completionHander block, I waited a long time but it still don't response anything. My internet connection is very fine.
So anyone know the solution? Or can you give me another library to do this.
Thank so much.
As it turned out in this and this Github issue conversations, the problem was on the server side. If anyone comes here looking for help, I suggest going through these libraries issue pages and trying to match your problem, or contact the creators of Jetfire and Starscream (if you are implementing them) because they are very friendly and do answer your upgrade/new feature issues pretty quickly!

How to use XCTest framework to test REST based native iOS appliction?

Tried to check out how to use XCTest framework for an application which is using REST web services. But did not find any good and complete example tutorial.
I have only some basic idea of XCTest but confused to use XCTest with REST application.
Can anybody give me some examples of how to use this. I just need the idea and direction and then I can go.
Note: If the application is a basic application, I know but my confusion is only for REST based iOS application testing.
I am using XCTestExpectation for testing client-server communication that is based on REST protocol.
Here is high level example:
- (void)testCreatingUserRequest {
// Initialize necessary objects
RestManager *restManager = ...
CreatingUserRequest *request = ...
// Execute test
XCTestExpectation *expectation = [self expectationWithDescription:#"Create User"];
[restManager createUserWithRequest:request completionHandler:^(NSDictionary *JSONObject, NSError *error) {
XCTAssertNotNil(JSONObject);
XCTAssertNotNil([User userWithJSONObject:JSONObject]);
XCTAssertNil(error);
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:30 handler:^(NSError *error) {
XCTAssertNil(error);
}];
}
This test cover such expectation cases:
1. Server has to return response in 30 seconds or less;
2. Server has to return valid JSON object with valid response code;
3. JSON object has to have correct structure for mapping to User object.

iOS large file download ~1GB files

For my bachelor thesis I have to implement an eLearning app for iOS. As you can see in my title, I have to download a file in the documents directory that has a size of nearly 1 or 2 GB. I'm very new at iOS-Development, so I would appreciate every tip how i can handle that.
Many thanks in advance!
Its good that you have read about NSURLConnection and ASIHTTP. But as you must be aware ASIHTTP is no longer actively developed/maintained. NSURLConnection is good to understand and learn the basics.
For day to day use, I'd suggest you use AFNetworking. It is simple to use and contains example for understanding how to use it.
For downloading large files it is recommended to write the downloaded data directly to a file rather than storing it in the memory. Using AFNetorking you can do this by,
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:#"download.zip" append:NO];
I have not tried downloading that large data myself, but I'm sure this will be a good start point for you.
AFNetworking: https://github.com/AFNetworking/AFNetworking
API documentation: http://cocoadocs.org/docsets/AFNetworking/2.0.0-RC2/
Happy coding!
Well, since this will very likely take a while to download I would definitely recommend doing this asynchronously using NSURLRequests and NSURLConnections.
My biggest concern though, is the pure size of this download and how this will likely not fit into RAM so this download may not actually be as easy as it seems. You can give it a shot, but what I would recommend is breaking this into multiple files/downloads if possible.
I will post code in a minute when I find code I have previously written.
Added Code
First off, make your class that needs to do the downloading to be an NSURLConnectionDelegate and `NSURLConnectionDataDelegate.
Then you can implement the download request as follows.
NSMutableData *linkData = [[NSMutableData alloc] init];
NSURLRequest *linkRequest = [[NSURLRequest alloc] initWithURL:youURL cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:10.0];
NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:linkRequest delegate:self];
The variable linkData should really be declared in the interface file and then allocated in the implementation, but for brevity I just created it as above.
Then you need the following methods which will be called
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[linkData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
// handle a fail
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
// do what you need when download finishes
}

Is it possible to use OCMock with NSURLConnection to inject simulated server response data?

I've spent all afternoon trawling the web for tutorials and examples of using OCMock but I've still no idea if its possible and if so how to use it in combination with NSURLConnection to set up test code to simulate a server sending data in response to HTTP POSTs or GETs.
Does anybody know of a handy tutorial for doing this?
UPDATE: I subsequently came across this:
how to unit test a NSURLConnection Delegate?
Yes, but I've found another package, OHHTTPStubs, to be a LOT easier for doing exactly what you're looking for:
https://github.com/AliSoftware/OHHTTPStubs
[OHHTTPStubs shouldStubRequestsPassingTest:^BOOL(NSURLRequest *request) {
return [request.URL.path isEqualToString:#"/api/oauth/access_token"];
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
return [OHHTTPStubsResponse responseWithFile:#"auth_login_passing.json" contentType:#"text/json" responseTime:OHHTTPStubsDownloadSpeedWifi];
}];

What are alternatives to NSURLConnection for chunked transfer encoding

I've checked for other questions relevant to this, but the only answer is "Use ASIHTTPRequest" as this is no longer being developed I wanted to ask what alternatives people are using, whilst working on our SDK I came across a lot of strange behaviour in NSURLConnection when receiving data from the server.
We tracked it down to the fact that NSURLConnection doesn't deal well with responses in chunked-encoding. Or at least so we read in this question here NSURLConnection and "chunked" transfer-coding
Some developers we were talking to say it gets better in iOS 5, we need to make sure that our SDK is backwards compatible with iOS 4.3 at least.
I want to confirm this is infact an issue in NSURLConnection, and how people are dealing with it.
All the alternatives I've found so far are based off of NSURLConnection and I'm assuming as such will have the same flaw. ASIHTTPRequest did in fact work because it's based a little lower than NSURLConnection, but were looking for alternatives in the knowledge it's no longer supported.
A list of other libraries looked at are:
Restkit,
ShareKit,
LRResty,
AFNetworking,
TTURLRequest
I'm aware there are similar questions here Is RESTKit a good replacement for ASIHTTPRequest? and here ASIHTTPRequest alternative But both of the solutions are based off NSURLConnection.
EDIT: I noticed I pointed to the wrong question at the start of my post, so thats updated. It points to a thread from 2008, and i've seen similar ones but none that are recent.
Chunked transfers are supported by NSURLConnection. I use them.
Define some props:
NSMutableData * responseData;
NSURLConnection * connection;
Establish a connection
NSURL *url = [NSURL URLWithString:#"...."];
self.responseData = [[NSMutableData alloc] initWithLength:0] ;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
Register your callback method for connection established
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// You may have received an HTTP 200 here, or not...
[responseData setLength:0];
}
Register your callback method for "chunk received"
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString* aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"This is my first chunk %#", aStr);
}
Register your "connection finished" callback:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}
And finally, register you "connection failed" callback:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Something went wrong...");
}
Just to chime in for the next person that gets here and still can't get NSURLConnection to work with chunk encoded data.
NSURLConnection will work with chunked encoding, but has non-disclosed internal behaviour such that it will buffer first 512 bytes before it opens the connection and let anything through IF Content-Type in the response header is "text/html", or "application/octet-stream". This pertains to iOS7 at least.
However it doesn't buffer the response if Content-Type is set to "text/json". So, whoever can't get chunked encoded NSURLConnection responses to work (i.e. callbacks aren't called) should check the response header and change it on the server to "text/json" if it doesn't break application behaviour in some other way.
There aren't any alternatives I'm aware of.
All the other libraries are built on top of NSURLConnection. Though you could use one of the non-iOS libraries, eg. libcurl.
ASIHTTPRequest is the only library I'm aware of that's built on top of the CFNetworking layer instead. This was (perhaps indirectly) the main reason the original developer stopped working on it - because it doesn't use NSURLConnection it has a lot of code.
It's probably not strictly correct to say that ASIHTTPRequest is no longer supported. It is true that the original developer no longer works on it, but if you look at the github commits you'll see it is still being worked on by other people. A lot of people still use it, for various reasons, myself included.
Having said all that, to go back to the problem you have: I'm not sure a 3 year old thread is necessarily a definitive reference to prove that a 1 year old release (ie. iOS 4.3) of NSURLConnection doesn't support chunked transfers. Chunked transfers are used so much on the web that it seems highly unlikely it would have a problem this large and obvious. It's possible there is something very particular to the server that you're using that is causing the issue.

Resources