How to parse one drive access token from url using objective-c - objective-c

I know it seems to be a silly question and URL parsing is easy to search, but I am really facing hard time to get the access token from the given URL below.
https://login.live.com/oauth20_desktop.srf?lc=1033#access_token=EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy%2bYnElFkAAcXV/IZULfKdn7RHvXY8CmB1J2c0PgYOldbBLp023y1BilHNHPQBeAflk4edFfbK2Fwdazg/mFi900PbS013mQqEE93d/4NlutyY9MK%2bU/q0QjInVfTPdxAQvc5RLevnMsqiS7H77Eg9K5YJCjQKTGE4ILhRO60UEyIXU2GgL4eNmYX3%2b64wrnL5q3QBmD%2bXFgkkk6EKvbncUdUeGWj%2bzlgKSiXT06QMK1LKhcFFrrOQj3spgnkyx5LmrDsBcDIAUxrMZ%2bF3kwutGEj7nfZTovuR/FT4XE221wLXZEpSydIwi20EGiGcYBsWw5mPqCRvPShL3dYd0%2bMLczvmu0iTQgK3kYDZgAACD9QFp4Vqf%2b9WAE2rBZLy%2bGoHEP3vivVKIYz2znPU/IRmNGmq8FRLhrwm/YcByRfIQOj9AGoqwL0wsgTj5lD4DIwlPWREI1zj%2bAKTGDZilkewxzncpwynF5ZAxHrT3iEjqyqAIpvtzY1xAiGj8Swqu1uLcEUS6p7c/Qk2HiSc1GY6%2bnc9epmkhSxIGi9HHTmnREaRxgbjbqLDZ5%2bLYhQLu9k%2bHjadfwoKFQpquN3NjbVi3LpZpHb2gfhr%2bf17XcLhEHb1xQnNg7rVVbvGe8FAgp9kZrkzzbFXY8jKzsjfRW%2bIUkNvcnLD39eFDs%2b/og2nxT8jE/qkKLW9wfgcDkfMnGWpIvQrCT6XrqvDaDCEVJ0rCiUG/L33SELLlBP3g8fLNjUOZ5K0ztksreaSH/4YCQdnS%2bopl2EG7PFl8ckDfzvVO5RqZS/SoSpa9h61regG37qzjLf2d%2bvxUPhW2FepeUwA28B&token_type=bearer&expires_in=3600&scope=wl.signin%20wl.offline_access%20onedrive.readwrite%20wl.basic&user_id=6c0a5d79b74cefa0c6d9d5f302a14876
My code
NSString* u = [[[[frame dataSource]request]URL]absoluteString];
NSString* output = nil;
if([u hasPrefix:#"https://login.live.com/oauth20_desktop.srf"])
{
NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
NSArray *urlComponents = [u componentsSeparatedByString:#"&"];
for (NSString *keyValuePair in urlComponents)
{
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:#"="];
NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];
[queryStringDictionary setObject:value forKey:key];
}
}
Result
{
"expires_in" = 3600;
"https://login.live.com/oauth20_desktop.srf?lc" = "EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAYQSbBaTYP1E4GlmB6vPpa9noNLSSg+FzA88BgdO2lFbr3EzR9POPhf417OAqXB7dlhZ7q/3AEhxthlBwFb3IebkElbeKUZll0QeIf7HniteFGJA0nD81xv01CHwjnJ0g/eIuh2GH8kE8/dL9seRMN4ngayEpV4Kp5/k3o1z9nDhtmn9/pZfspIlXo75Km9n2hqPAGt+7przBmYZZZGgLiQitQDCQEBidgKDfLjBmO5ZjbYFGuwCJz1Hmlsbs+e45MuF+VF4uk7ocAu8CQnFrYdVusPPS04QR2EzUkGt3uEBM7jmqnjZfM+EJ78kggmuPXuxkMarNsGiMYdzigNxIHEDZgAACE0dTsiQuAaFWAFL7tvmsSOprKe2jx4FrRgZhWn5F9vQTKw9thK63urFSY79m/CbLqQSlEMKLi4mRptJa+tXKFpg9anxHMyfvMSDQ5ryWK291qJX5W5Yv5syxSm3u6PEo8KM9WmeAdCW/trJzrCIVPrSdshzvI2N5Iu+SP9igWGDoWdE6uoH7G0ZA8gPn2v3NagzVNKUyIKuceiT3fI20nBCYx/6+N5Z/WWKmmkyuuAqo3kH5+FrGz2lz4F5tP0UOdYjY6q73RqUQMLwdJ2/3UNb3BcE/98nGbOgKMtCPPCx0GaPBwOPlVkvxqMa6oeNaHmArZNsyhwuvJEfWEbB+HLXtE5gYG5PziybUDeLa+uIJda9z0Tb9HRyMb+I2nA7+SMkhgITyo2OplaTMRVrKAGHViEDVSBMbspkbG6tV/nk/7SC3/cICXGPFX9u29sEcGe6l0onMQougQvhuXs90CFVNkVG8B";
scope = "wl.signin wl.offline_access onedrive.readwrite wl.basic";
"token_type" = bearer;
"user_id" = 6c0a5d79b74cefa0c6d9d5f302a14876;
}
Problem
As you can see in the above result, there is a key https://login.live.com/oauth20_desktop.srf?lc I think it should be Access_Token
Any suggestions are appreciated. Thank you so much.

My simple solution:
NSString *url = #"https://login.live.com/oauth20_desktop.srf?lc=1033#access_token=EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy%2bYnElFkAAcXV/IZULfKdn7RHvXY8CmB1J2c0PgYOldbBLp023y1BilHNHPQBeAflk4edFfbK2Fwdazg/mFi900PbS013mQqEE93d/4NlutyY9MK%2bU/q0QjInVfTPdxAQvc5RLevnMsqiS7H77Eg9K5YJCjQKTGE4ILhRO60UEyIXU2GgL4eNmYX3%2b64wrnL5q3QBmD%2bXFgkkk6EKvbncUdUeGWj%2bzlgKSiXT06QMK1LKhcFFrrOQj3spgnkyx5LmrDsBcDIAUxrMZ%2bF3kwutGEj7nfZTovuR/FT4XE221wLXZEpSydIwi20EGiGcYBsWw5mPqCRvPShL3dYd0%2bMLczvmu0iTQgK3kYDZgAACD9QFp4Vqf%2b9WAE2rBZLy%2bGoHEP3vivVKIYz2znPU/IRmNGmq8FRLhrwm/YcByRfIQOj9AGoqwL0wsgTj5lD4DIwlPWREI1zj%2bAKTGDZilkewxzncpwynF5ZAxHrT3iEjqyqAIpvtzY1xAiGj8Swqu1uLcEUS6p7c/Qk2HiSc1GY6%2bnc9epmkhSxIGi9HHTmnREaRxgbjbqLDZ5%2bLYhQLu9k%2bHjadfwoKFQpquN3NjbVi3LpZpHb2gfhr%2bf17XcLhEHb1xQnNg7rVVbvGe8FAgp9kZrkzzbFXY8jKzsjfRW%2bIUkNvcnLD39eFDs%2b/og2nxT8jE/qkKLW9wfgcDkfMnGWpIvQrCT6XrqvDaDCEVJ0rCiUG/L33SELLlBP3g8fLNjUOZ5K0ztksreaSH/4YCQdnS%2bopl2EG7PFl8ckDfzvVO5RqZS/SoSpa9h61regG37qzjLf2d%2bvxUPhW2FepeUwA28B&token_type=bearer&expires_in=3600&scope=wl.signin%20wl.offline_access%20onedrive.readwrite%20wl.basic&user_id=6c0a5d79b74cefa0c6d9d5f302a14876";
NSURLComponents *components = [NSURLComponents componentsWithString:[url stringByReplacingOccurrencesOfString:#"#" withString:#"&"]];
//get query items
NSLog(#"%#", components.queryItems);
result will be:
(
"<NSURLQueryItem 0x17541ae0> {name = lc, value = 1033}",
"<NSURLQueryItem 0x1753f7f0> {name = access_token, value = EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAcXV/IZULfKdn7RHvXY8CmB1J2c0PgYOldbBLp023y1BilHNHPQBeAflk4edFfbK2Fwdazg/mFi900PbS013mQqEE93d/4NlutyY9MK+U/q0QjInVfTPdxAQvc5RLevnMsqiS7H77Eg9K5YJCjQKTGE4ILhRO60UEyIXU2GgL4eNmYX3+64wrnL5q3QBmD+XFgkkk6EKvbncUdUeGWj+zlgKSiXT06QMK1LKhcFFrrOQj3spgnkyx5LmrDsBcDIAUxrMZ+F3kwutGEj7nfZTovuR/FT4XE221wLXZEpSydIwi20EGiGcYBsWw5mPqCRvPShL3dYd0+MLczvmu0iTQgK3kYDZgAACD9QFp4Vqf+9WAE2rBZLy+GoHEP3vivVKIYz2znPU/IRmNGmq8FRLhrwm/YcByRfIQOj9AGoqwL0wsgTj5lD4DIwlPWREI1zj+AKTGDZilkewxzncpwynF5ZAxHrT3iEjqyqAIpvtzY1xAiGj8Swqu1uLcEUS6p7c/Qk2HiSc1GY6+nc9epmkhSxIGi9HHTmnREaRxgbjbqLDZ5+LYhQLu9k+HjadfwoKFQpquN3NjbVi3LpZpHb2gfhr+f17XcLhEHb1xQnNg7rVVbvGe8FAgp9kZrkzzbFXY8jKzsjfRW+IUkNvcnLD39eFDs+/og2nxT8jE/qkKLW9wfgcDkfMnGWpIvQrCT6XrqvDaDCEVJ0rCiUG/L33SELLlBP3g8fLNjUOZ5K0ztksreaSH/4YCQdnS+opl2EG7PFl8ckDfzvVO5RqZS/SoSpa9h61regG37qzjLf2d+vxUPhW2FepeUwA28B}",
"<NSURLQueryItem 0x1753f3d0> {name = token_type, value = bearer}",
"<NSURLQueryItem 0x1753f660> {name = expires_in, value = 3600}",
"<NSURLQueryItem 0x1753fd60> {name = scope, value = wl.signin wl.offline_access onedrive.readwrite wl.basic}",
"<NSURLQueryItem 0x1757daf0> {name = user_id, value = 6c0a5d79b74cefa0c6d9d5f302a14876}"
)
Appended By Vikas Bansal
/// the given below code will parse url components and get you the access token in a NSString variable]
NSArray *queryItems = components.queryItems;
NSString *TheToken = [self valueForKey:#"access_token" fromQueryItems:queryItems];
NSLog(TheToken);
/// add this funciton in you .m file
- (NSString *)valueForKey:(NSString *)key
fromQueryItems:(NSArray *)queryItems
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name=%#", key];
NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate]
firstObject];
return queryItem.value;
}

Related

Unable to convert UTF-8 text from NSDictionary in Objective-C

Im using foursquare API to get some locations around me, but when the name of that place wasn't in english, the name will be like follows:
name = "\U0645\U0633\U062c\U062f \U0627\U0644\U0633\U064a\U062f\U0629 \U0639\U0627\U0626\U0634\U0629 | Aisha Mosque";
i tried to convert the response to a UTF-8 but nothing changed.
Here is my code:
-(void)setUpLocations{
NSURL *url = [NSURL URLWithString: #"https://api.foursquare...."];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Response: %#",[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"]);
}
And the log result is:
contact = {
};
id = 51712507498ec4e8c5ae9f48;
likes = {
count = 0;
groups = (
);
};
location = {
address = Abdoun;
cc = JO;
city = Amman;
country = Jordan;
distance = 3819;
lat = "31.95406043797281";
lng = "35.88095228186612";
};
name = "\U0645\U0633\U062c\U062f \U0627\U0644\U0633\U064a\U062f\U0629 \U0639\U0627\U0626\U0634\U0629 | Aisha Mosque";
restricted = 1;
stats = {
checkinsCount = 43;
tipCount = 2;
usersCount = 23;
};
verified = 0;
},
Any Suggestions ??
EDIT:
here is how i extract the data from the dictionary:
NSDictionary *dic = [[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"] copy];
namesArray = [[NSArray alloc]initWithArray:[self removeWhiteSpaces:[dic valueForKey:#"name"]]];
-(NSArray *)removeWhiteSpaces:(NSDictionary *)dic{
NSString *str = [NSString stringWithFormat:#"%#",dic];
NSString *str2 = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSString *secondString = [str2 stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *thirdString = [secondString stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *forthString = [thirdString stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *fifthString = [forthString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *items = [fifthString componentsSeparatedByString:#","];
return items;
}
And in the UITableView:
cell.textLabel.text = [NSString stringWithFormat:#"Name: %# ",[namesArray objectAtIndex:indexPath.row] ];
Update
After trying #Martin R answer i got the same results:
NSDictionary *dic = [[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"] copy];
NSString *value =[dic valueForKey:#"name"];
NSLog(#"%#", value);
UILabel *lbl = [[UILabel alloc]initWithFrame:self.view.frame];
lbl.numberOfLines = 0;
lbl.text = [NSString stringWithFormat:#"%#",value];;
[self.view addSubview:lbl];
and here is an image of the result
There is no problem.
NSLog() calls the description method of NSDictionary and NSArray, and that prints all non-ASCII characters as \Unnnn escape sequence.
If you extract the string values from the dictionary and print that you will see
that everything is correct.
Simple example:
NSDictionary *dict = #{ #"currency": #"€" };
NSLog(#"%#", dict);
// Output: { currency = "\U20ac"; }
NSString *value = dict[#"currency"];
NSLog(#"%#", value);
// Output: €
UPDATE: The problem seems to be in your removeWhiteSpaces: method, because
NSString *str = [NSString stringWithFormat:#"%#",dic];
already uses the description method to convert the dictionary to a string,
and the following stringByReplacingOccurrencesOfString calls are a (sorry!) very bad
method to fix that.
You should access the dictionary keys with objectForKey instead, or enumerate
the dictionary with for (NSString *key in dic) { ... } and build the desired
array.
UPDATE 2: From the JSON data (posted in chat discussion) it seem that you just need
NSArray *itemsArray = json[#"response"][#"groups"][0][#"items];
NSArray *namesArray = [itemsArray valueForKey:#"name"];
Note that "groups" is an array with one element.
Try to use this one..
[NSString stringWithUTF8String:]

Converting Json Object to String - Objective C

Imagine I make an request to my api that return an mysql_query("Select * from user where id=1").
After the request is done, it returns the user info in json.
I do some debuging, NSlog(#"JSON : %#",json); and it gives me this:
JSON : (
{
aboutme = "";
active = 0;
birthday = "1992-10-14";
"city_id" = 0;
email = "test#test.com";
fbid = "";
firstname = test;
gender = 1;
id = 162;
lastname = test;
password = "$2a$12$8iy.sGr.4V/Ea3GfHZe0m.SLDrvoSj3/wYRlWsNce1yyCMeCbDrMC";
"phone_number" = "";
"recovery_date" = "0000-00-00 00:00:00";
"register_date" = "2013-06-06 02:44:20";
salt = "8iy.sGr.4V/Ea3GfHZe0m";
"user_type_id" = 1;
username = test;
}
)
Now I parse it with AFJONDecode and when I get the [json valueForKey:#"username"]; and debug it ( NSlog(#"username = %#",[json valueForKey#"username"]); ) and I get this:
username = (
testeteste739
)
It gives me an object ( because in the Json, the username = test and not username = "test").
So, how can i convert this object to string?
** UPDATE **
I resolve it by the following way:
NSArray *username = [JSON valueForKey:#"username"];
username = [username objectAtIndex:0];
Is there any better way to overpass this?
Thanks
As JSON is a dictionary object, so you can get your json data to JSONDic NSDictionary variable and parse it to string as follows:-
NSDictionary *JSONDic=[[NSDictionary alloc] init];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:JSONDic
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

objective-c: read an array create by json

I begin in Ios dev and I got some troubles to manipulate an array create by Json :
I call in my app a web Service which return me data :
{evenements =(
({
dateEvenement ={
1 = "01-01-2013";
2 = "02-01-2013";
3 = "03-01-2013";
4 = "04-01-2013";
};
idEvenement = 61;
nbrInvite = 1;
nomEvenement = "My event Name";
nomUtilisateur = "Lucas ";
}
),
);
}
I'm able to get all the values by the following code except for "dateEvenement" :
NSArray *msgList;
msgList = [ jsonResults objectForKey:#"evenements" ];
for (NSDictionary *evenements in msgList) {
for (NSDictionary *evenement in evenements ) {
NSString *idEvenement = [evenement objectForKey:#"idEvenement"];
NSString *nomUtilisateur = [evenement objectForKey:#"nomUtilisateur"];
NSString *nomEvenement = [evenement objectForKey:#"nomEvenement"];
NSString *nbrInvite = [evenement objectForKey:#"nbrInvite"];
NSArray *dates = [ evenement objectForKey:#"dateEvenement" ];
}
}
Can you help me for getting datas of "dateEvenement"
Well in your JSON the dateEvenement isn't an Array but a dictionary:
NSDictionary *dates = [ evenement objectForKey:#"dateEvenement"];
for(NSNumber *key in dates) {
NSString *dateString = [dates objectForKey:key];
NSLog(%# : %#, key, dateString);
}
As declared in your JSON example the key's for the dictionary are numbers, thus you should NSNumber object for the key type.

Extracting number from NSString

I have an NSString which when logged gives me an answer like this one:
Response: oauth_token_secret=6h8hblp42jfowfy&oauth_token=9tmqsojggieln6z
The two numbers change every single time.
Is there a way to extract the two numbers and create two strings with one of each??
Like:
NSString *key = #"9tmqsojggieln6z";
//copy the string in a new string variable
NSMutableString *auth_token = [NSMutableString stringWithString:response];
NSRange match = [auth_token rangeOfString: #"&oauth_token="];
[auth_token deleteCharactersInRange: NSMakeRange(0, match.location+13)];
//auth_token will now have the auth token string
NSMutableString *auth_token_secret = [NSMutableString stringWithString:response];
NSRange range1 = [auth_token_secret rangeOfString:[NSString stringWithFormat:#"&oauth_token=%#", auth_token]];
[auth_token_secret deleteCharactersInRange:range1];
NSRange range2 = [auth_token_secret rangeOfString:#"oauth_token_secret="];
[auth_token_secret deleteCharactersInRange: range2];
//auth_token_secret will have the required secret string.
I had the same problem. As response I get the ids of objects sometimes as string sometimes as numbers. Then I wrote a category for NSDictionary which has the following method:
- (NSString *)stringFromStringOrNumberForKey:(NSString *)key
{
id secret = [self objectForKey:key];
if ([secret isKindOfClass:[NSNumber class]]) {
NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
secret = [numberFormatter stringFromNumber:secret];
}
return secret;
}
I would try the following:
NSString *_response = #"oauth_token_secret=6h8hblp42jfowfy&oauth_token=9tmqsojggieln6z";
NSMutableDictionary *_dictionary = [[NSMutableDictionary alloc] init];
NSArray *_parameters = [_response componentsSeparatedByString:#"&"];
for (NSString *_oneParameter in _parameters) {
NSArray *_keyAndValue = [_oneParameter componentsSeparatedByString:#"="];
[_dictionary setValue:[_keyAndValue lastObject] forKey:[_keyAndValue objectAtIndex:0]];
}
// reading the values
NSLog(#"token_secret : %#", [_dictionary valueForKey:#"oauth_token_secret"]);
NSLog(#"token : %#", [_dictionary valueForKey:#"oauth_token"]);

complex JSON parsing using Objective-C

{
"Flight1":{
"3":{
"id":"10",
"name":"JumboJet1B",
"level":"1",
"category":"1",
"energy":"10",
"bonus":"10",
"completed":0
},
"4":{
"id":"10",
"name":"JumboJet1B",
"level":"1",
"category":"1",
"energy":"10",
"bonus":"10",
"completed":0
}
}
}
This was the json output
How can I parse inside the items of 3 and 4, say getting the id, energy and name
Thanks!
If the order inside Flight1 doesn’t matter, the following should work:
NSDictionary *flights = … // result from a JSON parser
NSDictionary *flight1 = [flights objectForKey:#"Flight1"];
for (NSString *key in [flight1 allKeys]) {
NSDictionary *flight1Entry = [flight1 objectForKey:key];
NSString *entryId = [flight1Entry objectForKey:#"id"];
NSString *entryName = [flight1Entry objectForKey:#"name"];
NSString *entryEnergy = [flight1Entry objectForKey:#"energy"];
…
}
Otherwise, if you want the keys sorted according to their numeric value:
NSDictionary *flights = … // result from a JSON parser
NSDictionary *flight1 = [flights objectForKey:#"Flight1"];
NSArray *flight1Keys = [[flight1 allKeys] sortedArrayUsingComparator:^(id o1, id o2) {
NSInteger i1 = [o1 integerValue];
NSInteger i2 = [o2 integerValue];
NSComparisonResult result;
if (i1 > i2) result = NSOrderedDescending;
else if (i1 < i2) result = NSOrderedAscending;
else result = NSOrderedSame;
return result;
}];
for (NSString *key in flight1Keys) {
NSDictionary *flight1Entry = [flight1 objectForKey:key];
NSString *entryId = [flight1Entry objectForKey:#"id"];
NSString *entryName = [flight1Entry objectForKey:#"name"];
NSString *entryEnergy = [flight1Entry objectForKey:#"energy"];
…
}
Assuming that you are using the json framework you could access it like this:
NSDictionary *jsonDict = [jsonString JSONValue];
NSString *id = [[[jsonDict objectForKey:#"Flight1"] objectForKey:#"3"] objectForKey:#"id"];
This assumes alot, so make use of try except blocks or iterate through the different levels.