Supertecnoboff
Supertecnoboff

Reputation: 6606

Programmatically delete parts of NSString

I have an iOS app which connects to a server via OAuth 2.0. I get returned an access token in this form:

{accessToken="521515.ab6dc96.51dca3d53c4236d2d4f4460b151bc58d6ec91e14"}

And I store that in a NSString. The problem I am having is that I ONLY need the part which is in the quotation marks. How can I extract that?

UPDATE

Here us my code:

GTMOAuth2Authentication *auth_instagram;
auth_instagram = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:@"Instagram" clientID:kMyClientID_instagram clientSecret:kMyClientSecret_instagram];

NSLog(@"%@", auth_instagram);

Printed in the Xcode console is:

GTMOAuth2Authentication 0xb2c0a80: {accessToken="541019.ab6dc96.51dc0d264d2d4f60b151bc8d6ec91e14"} 

Upvotes: 0

Views: 152

Answers (5)

Martin R
Martin R

Reputation: 539685

If I read the class definition at http://code.google.com/p/gtm-oauth2/source/browse/trunk/Source/GTMOAuth2Authentication.h correctly, GTMOAuth2Authentication has a

@property (retain) NSString *accessToken;

so that you can just do

NSString *token = auth_instagram.accessToken;

to get the token as a string.

Remark: Your output

{accessToken="521515.ab6dc96.51dca3d53c4236d2d4f4460b151bc58d6ec91e14"}

is the result of calling the description method of GTMOAuth2Authentication. This is not JSON. JSON would look like

{ "accessToken" : "521515.ab6dc96.51dca3d53c4236d2d4f4460b151bc58d6ec91e14" }

Upvotes: 2

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

What you got there is valid JASON. Try the following:

NSDictionary *loginInfo = [NSJSONSerialization JSONObjectWithData:[@"{accessToken=\"521515.ab6dc96.51dca3d53c4236d2d4f4460b151bc58d6ec91e14\"}" dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
NSString *aToken = [loginInfon objectForKey:@"accessToken"];

Upvotes: 0

Sarfaraz Khan
Sarfaraz Khan

Reputation: 592

 NSDictionary *dic =[NSJSONSerialization JSONObjectWithData: [YourString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
//yourstring is the string in which u store and &e is just an NSError u can create urself like  NSError *e;

  NSString access_Token=[dic objectForKey:@"accessToken"];

Upvotes: 0

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81848

The right way would be to parse the whole string using the correct format/parser, in this case probably NSJSONSerialization and extract the value from the accessToken element.

NSDictionary *parsedData = [JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:NULL];
NSString *value = parsedData[@"accessToken"];

Upvotes: 2

Morion
Morion

Reputation: 10860

NSArray* components = [accessStr componentsSeparatedByString: "\""];
NSString* requiredStr = [components objectAtIndex: 1];

Upvotes: 0

Related Questions