I'm struggling to get an iOS application to connect to my node server running OpenTok. Things work fine when I hard code the values in, but I want dynamic sessions and tokens, hence my question.
I'm able to successfully create a token on the server side, it looks like:
[
{
"_id": "*******",
"token": "***********************",
"sessionId": "********",
}
]
I can also retrieve it successfully in the iOS app with:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://path/to/json"]];
NSData *theData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:nil];
NSMutableArray *newJSON = [NSJSONSerialization JSONObjectWithData:theData options:NSJSONReadingMutableContainers error:nil];
NSString* kToken = [newJSON valueForKey:@"sessionId"];
NSString* kSessionId = [newJSON valueForKey:@"token"];
I can print the values to console with:
NSLog(@"Value of kToken = %@", kToken);
NSLog(@"Value of kSessionId = %@", kSessionId);
So I know it is being read in correctly, but regardless I still get errors:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x14d97950
I am rather new to iOS so maybe I've bitten off more than I can chew here but any advice in the right direction would be great. There doesn't seem to be anything in the documentation regarding how to properly get the token from your server through iOS.
This JSON:
[
{
"_id": "*******",
"token": "***********************",
"sessionId": "********",
}
]
is inside an array.
This code:
NSString* kToken = [newJSON valueForKey:@"sessionId"];
asks the array (newJSON
) to extract sessionId
from each of its elements, and return them in a new array (that's what valueForKey:
does). So, you thing you get an NSString
, but you don't, you really get an NSArray
. So, later, when you use it as a string you get an exception, because the array doesn't have the length
method.
Try this:
NSString* kToken = [[newJSON objectAtIndex:0] objectForKey:@"sessionId"];
or preferably change the JSON so it doesn't return an object in an array.
Note that you should basically always use objectForKey:
instead of valueForKey:
(well, until you properly understand what the latter is doing).