Programmatically delete parts of NSString - objective-c

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"}

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" }

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"];

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

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"];

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"];

Related

How to find attribute of root node in touch xml?

NSString *xml = #"<?xml version="1.0" encoding="ISO-8859-15"?>
<ServerDateTime DateRequested="" DateSent="20141013_114855">
<DateTime>20141013_114857</DateTime>
</ServerDateTime>";
In above xml, how to find the attribute value of 'DataSent'?
I have tried by following, but i didn't get the value.
CXMLDocument *documentParser = [[CXMLDocument alloc]initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *arrayResult = [documentParser nodesForXPath:#"//ServerDateTime" error:nil];
for(CXMLElement *element in arrayResult){
NSString *value = [element name];
if ([value isEqualToString:#"ServerDateTime"]) {
NSString *newLastSyncDate = [[element attributeForName:#"DataSent"] stringValue]; //it gives nil..
}
}
You may want to use XPath-queries to search for elements inside a XML. You have to look up if CXML supports this.
Maybe also take a look at this question.
There someone is searching for a given attribute with an XPath-query.

how to convert an array into string? [duplicate]

In my iPhone aplication I have a list of custom objects. I need to create a json string from them. How I can implement this with SBJSON or iPhone sdk?
NSArray* eventsForUpload = [app.dataService.coreDataHelper fetchInstancesOf:#"Event" where:#"isForUpload" is:[NSNumber numberWithBool:YES]];
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *actionLinksStr = [writer stringWithObject:eventsForUpload];
and i get empty result.
This process is really simple now, you don't have to use external libraries,
Do it this way, (iOS 5 & above)
NSArray *myArray;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
I love my categories so I do this kind of thing as follows
#implementation NSArray (Extensions)
- (NSString*)json
{
NSString* json = nil;
NSError* error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return (error ? nil : json);
}
#end
Although the highest voted answer is valid for an array of dictionaries or other serializable objects, it's not valid for custom objects.
Here is the thing, you'll need to loop through your array and get the dictionary representation of each object and add it to a new array to be serialized.
NSString *offersJSONString = #"";
if(offers)
{
NSMutableArray *offersJSONArray = [NSMutableArray array];
for (Offer *offer in offers)
{
[offersJSONArray addObject:[offer dictionaryRepresentation]];
}
NSData *offersJSONData = [NSJSONSerialization dataWithJSONObject:offersJSONArray options:NSJSONWritingPrettyPrinted error:&error];
offersJSONString = [[NSString alloc] initWithData:offersJSONData encoding:NSUTF8StringEncoding] ;
}
As for the dictionaryRepresentation method in the Offer class:
- (NSDictionary *)dictionaryRepresentation
{
NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
[mutableDict setValue:self.title forKey:#"title"];
return [NSDictionary dictionaryWithDictionary:mutableDict];
}
Try like this Swift 2.3
let consArray = [1,2,3,4,5,6]
var jsonString : String = ""
do
{
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(consArray, options: NSJSONWritingOptions.PrettyPrinted)
{
jsonString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
}
}
catch
{
print(error)
}
Try like this,
- (NSString *)JSONRepresentation {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithObject:self];
if (!json)
[jsonWriter release];
return json;
}
then call this like,
NSString *jsonString = [array JSONRepresentation];
Hope it will helps you...
I'm a bit late to this party, but you can serialise an array of custom objects by implementing the -proxyForJson method in your custom objects. (Or in a category on your custom objects.)
For an example.

JSON to NSDictionary - How to check the boolean type

I get JSON from site using this code:
+(NSDictionary *)parseJSONFromURLString:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonAsString = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:nil];
NSData *json = [jsonAsString dataUsingEncoding:NSUTF8StringEncoding];
return [NSJSONSerialization JSONObjectWithData:json options:0 error:nil];
}
When I am calling this method and debugging:
NSDictionary *response = [APIUtils parseJSONFromURLString:[queryBuilder questionsFromTime:time WithPageSize:100 WithPage:1]];
I can look at jsonAsString variable in the parseJSONFromURLString (NSString) method I can see the element "has_more" with value true:
..., "has_more":true, ....
But If I look at responseVariable (NSDictionary) I see next picture:
The value have __NSCFBoolean type and 0X7fff79d377f0 value.
How can I convert this type to BOOL and check it as true or false ?
Using this if statement should detect if the value for that key is true or false.
if([[response objectForKey:#"has_more"] isEqual:[NSNumber numberWithBool:true]]){
//hits here if this value is true
}else{
//and here if it's not.
}
I hope this is what you're looking for.
NSNumber class has the method:
- (BOOL)boolValue
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/Reference/Reference.html#//apple_ref/doc/uid/20000178-boolValue
It's actually a NSNumber, you can get its boolValue.

Play with NSDictionary in console in Xcode

New to Xcode and obj-c.
Is it possible to sort through data structures in the console like you with JavaScript?
-(void)fetchInfo
{
NSURL *url = [NSURL URLWithString:#"http://someurl"];
NSData *jsonResults = [NSData dataWithContentsOfURL:url];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonResults
options:0
error:NULL];
NSLog(#"CitiBike Results = %#", dictionary);
}
The results are logged, but I now want to play with the returned dictionary
If you make a mutable copy, you can fiddle with that in the console
NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];
then
p mutableDictionary[#"key"] = #"Hello, World!"
EDIT: you can also store it in a convenience variable in lldb like
expr NSMutableDictionary *$md = mutableDictionary
so that if it goes out of scope, as long as it's alive, you can still access it in the debugger like
p $md[#"key"] = #"Convenience!"

How to convert json string to nsdictionary on json parser framework on objective c

I am trying to convert raw json string to NSDictionary. but on NSDictionary i got different order of objects as on json string but i need exactly same order in NSDictionary as on json string. following is code i have used to convert json string
SBJSON *objJson = [[SBJSON alloc] init];
NSError *error = nil;
NSDictionary *dictResults = [objJson objectWithString:jsonString error:&error];
From NSDictionary's class reference:
The order of the keys is not defined.
So, basically you can't do this when using a standard NSDictionary.
However, this may be a good reason for subclassing NSDictionary itself. See this question about the details.
NSDictionary is an associative array and does not preserve order of it's elements. If you know all your keys, then you can create some array, that holds all keys in correct order (you can also pass it with your JSON as an additional parameter). Example:
NSArray* ordered_keys = [NSArray arrayWithObjects: #"key1", #"key2", #"key3", .., nil];
for(NSString* key is ordered_keys) {
NSLog(#"%#", [json_dict valueForKey: key]);
}
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"loans"]; //2
NSLog(#"loans: %#", latestLoans); //3
Source: Follow this link http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Good tutorial but works only on iOS5