iPhone Google Data API HTTP Protocol, Auth Token from string - iphone

Google Docs returns a long 3 line string when supplied with credentials. This is the format
SID=stuff...
LSID=stuff...
Auth=long authorization token
if I have it stored in NSString, what is the best function to trim all the way up to the "=" behind Auth, and keep the rest?
NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:theResponse error:NULL];
NSString *newDataString = [[NSString alloc]initWithData:returnedData encoding:NSUTF8StringEncoding];
NSString *authToken = [newDataString ____________];

I figured out the answer on my own through the documentation for NSString:
there is a method called
-(NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator {
that gives back an array of different strings, separated by an NSCharacterSet.
There is a class method of NSCharacterSet called
+(NSCharacterSet *)newLineCharacterSet {
that will split up a string with the newline symbol into pieces, so each line becomes its own object. Here is how it works:
NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:NULL];
NSString *newDataString = [[NSString alloc]initWithData:returnedData encoding:NSUTF8StringEncoding];
NSCharacterSet *theCharacterSet = [NSCharacterSet newlineCharacterSet];
NSArray *lineArray = [newDataString componentsSeparatedByCharactersInSet:theCharacterSet];
Now, the object lineArray contains different strings, each one is the start of a new line.
You're welcome!

If it is a three-line string, I assume it is split with newline (\n) characters.
NSArray *_authComponents = [threeLineString componentsSeparatedByString:#"\n"];
NSString *_sidToken = [_authComponents objectAtIndex:0]; // "SID=..."
NSString *_lsidToken = [_authComponents objectAtIndex:1]; // "LSID=..."
NSString *_authToken = [_authComponents objectAtIndex:2]; // "Auth=..."
Hopefully that gets you started. Once you have individual components, you can repeat on the equals (=) character, for example.

Related

NSString like '\uf003" replace '\' with some other string in in obj c

i need to send smiley to other user through iphone app ,so i need to replace \ string with some unique string in obj c.
here if your string is #"\ud83d\ude04" then it is give error "Invalid Character" so put this ' special character and then use it ..
NSString *str = #"\'ud83d\'ude04";//// here if your string is #"\ud83d\ude04" then it is give error "Invalid Character" so put this ' special character and then use it
NSString *smileWithString = [str stringByReplacingOccurrencesOfString:#"\'" withString:#":)"];
[smileWithString retain];
NSLog(#"\n\n SmileString %# Str %#",smileWithString);
Update:
Here’s how to convert NSString to NSData – it’s really simple:
NSString *myString = #"Some String";
NSData *myData = [myString dataUsingEncoding:NSUTF8StringEncoding];
And what about the reverse conversion, i.e. how to convert NSData to NSString? Here’s one quick way:
NSString *myString = [NSString stringWithFormat:#"%.*s",[myData length], [myData bytes]];
Use encoding of NSString and when need to use or show string decode it.
Refer base64-encoding link.
Your looking for stringByReplacingOccurrencesOfString that should do the trick.
NSString *newString = [oldString stringByReplacingOccurrencesOfString:#"\" withString:#"uniqueString"];

Ampersand in POST request causing havoc

I have a simple POST coming from my iphone app. Its working fine, except passing an ampersand causes the backend to break - it's almost like its treating it like a GET request (ampersands seperate the variable names). Do I need to do some kind of encoding first? Here is the code:
NSString *content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", str, emailAddress.text];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.myurl.com/myscript.php"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
I had this issue in iOS7 and the accepted answer didn't work at all (actually, that is my standard when sending data to the backend). The ampersand was breaking in the backend side, so I had to replace the & by %26. The backend was being done in python and the code was legacy and was using ASI.
Essentially I have done the following:
NSString *dataContent = [NSString stringWithFormat:#"text=%#",
[json stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
dataContent = [dataContent stringByReplacingOccurrencesOfString:#"&"
withString:#"%26"];
ByAddingPercent....... will not work as & is a valid URL character.
I needed to send a JSON with & in it, it is the same idea though;
NSString *post = [NSString stringWithFormat:#"JSON=%#", (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)jsonString, NULL, CFSTR(":/?#[]#!$&’()*+,;="), kCFStringEncodingUTF8))];
"jsonString" towards the end is what is converted.
Edit: As stringByAddingPercentEscapesUsingEncoding: should be used to encode parts of the query, not the whole one, you should be using another method instead.
Unfortunately, Foundation doesn't provide such a method, so you need to reach to CoreFoundation:
- (NSString *)stringByURLEncodingString:(NSString *)string {
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)string,
NULL, // or (__bridge CFStringRef)(#"[].")
(__bridge CFStringRef)(#":/?&=;+!##$()',*"),
kCFStringEncodingUTF8
);
}
You can use
- stringByAddingPercentEscapesUsingEncoding:
In your case it will look like this:
NSString * content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [emailAddress.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
You can do this in this way, too:
NSString *dataStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *emailStr = [emailAddress.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *content = [[NSString alloc] initWithFormat:#"data=%#&email=%#", dataStr, emailStr];
I'm not sure if this will work in your case, but you could try %38 to try and encode the ampersand.

Problem creating url

I want to create a url as below
http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false
I used the following code to create this
NSURL *jsonURL;
NSString *strurl = [[NSString alloc]initWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false"];
jsonURL = [NSURL URLWithString:strurl];
[strurl release];
NSLog(#"json Url%#",jsonURL);
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
if(jsonData == nil){
//NSLog(#"Data NIL .....");
}
else{
SBJSON *json = [[SBJSON alloc] init];
NSError *error = nil;
dic = [json objectWithString:jsonData error:&error];
[json release];
}
But every time I get jsonURL to be nil .
I think the problem is due to "|". Has someone come across same issue? If yes, can you help me out?
Try
[NSURL URLWithString:[strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
The documentation for URLWithString says:
The string with which to initialize the NSURL object. Must conform to RFC 2396.
... which e.g. mentions:
Other characters are excluded because
gateways and other transport agents
are known to sometimes modify such
characters, or they are used as
delimiters.
unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
Data corresponding to excluded
characters must be escaped in order to
be properly represented within a URI.
Thus escape them properly as slf suggested.
Also, just use a string constant for predefined strings:
NSString *strurl = #"http://....";
As for your URL issue, Georg is right:
NSURL *jsonURL = [NSURL URLWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize%3Atrue%7CBarossa+Valley,SA%7CClare,SA%7CConnawarra,SA%7CMcLaren+Vale,SA&sensor=false"];
Fixed that issue for me.
However, the next bit:
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
Is deeply troubling. You should never do synchronous data reads on the main thread. initWithContentsOfURL is going to spawn a synchronous NSURLConnection to go fetch that data and might return sometime before sunday, but you never know. (This method is ok for filesystem loads, where things are much more deterministic)
Look into an asynchronous loading API like NSURLConnection from Apple, or better yet ASIHTTPRequest, about which there is ample documentation online.
Happy webservicing!
I think, the root of cause is your string creating method.
NSString *strurl = [[NSString alloc]initWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false"];
Try with ...
NSString *strurl = [[NSString alloc]initWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false"];

NSString - how to go from "ÁlgeBra" to "Algebra"

Does anyone knows hoe to get a NSString like "ÁlgeBra" to "Algebra", without the accent, and capitalize only the first letter?
Thanks,
RL
dreamlax has already mentioned the capitalizedString method. Instead of doing a lossy conversion to and from NSData to remove the accented characters, however, I think it is more elegant to use the stringByFoldingWithOptions:locale: method.
NSString *accentedString = #"ÁlgeBra";
NSString *unaccentedString = [accentedString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
NSString *capitalizedString = [unaccentedString capitalizedString];
Depending on the nature of the strings you want to convert, you might want to set a fixed locale (e.g. English) instead of using the user's current locale. That way, you can be sure to get the same results on every machine.
NSString has a method called capitalizedString:
Return Value
A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
NSString *str = #"AlgeBra";
NSString *other = [str capitalizedString];
NSLog (#"Old: %#, New: %#", str, other);
Edit:
Just saw that you would like to remove accents as well. You can go through a series of steps:
// original string
NSString *str = #"ÁlgeBra";
// convert to a data object, using a lossy conversion to ASCII
NSData *asciiEncoded = [str dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
// take the data object and recreate a string using the lossy conversion
NSString *other = [[NSString alloc] initWithData:asciiEncoded
encoding:NSASCIIStringEncoding];
// relinquish ownership
[other autorelease];
// create final capitalized string
NSString *final = [other capitalizedString];
The documentation for dataUsingEncoding:allowLossyConversion: explicitly says that the letter ‘Á’ will convert to ‘A’ when converting to ASCII.
Here's a step by step example of how to do it. There's room for improvement, but you get the basic idea......
NSString *input = #"ÁlgeBra";
NSString *correctCase = [NSString stringWithFormat:#"%#%#",
[[input substringToIndex:1] uppercaseString],
[[input substringFromIndex:1] lowercaseString]];
NSString *result = [[[NSString alloc] initWithData:[correctCase dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding] autorelease];
NSLog( #"%#", result );

Creating an array from a text file read from a URL

I am reading a text file from a URL and want to parse the contents of the file into an array. Below is a snippet of the code I am using. I want to be able to place each line of the text into the next row of the array. Is there a way to identify the carriage return/line feed during or after the text has been retrieved?
NSURL *url = [NSURL URLWithString:kTextURL];
textView.text = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
When separating by newline characters it's best to use the following procedure:
NSCharacterSet *newlines = [NSCharacterSet newlineCharacterSet];
NSArray *lineComponents = [textFile componentsSeparatedByCharactersInSet:newlines];
This ensures that you get lines separated by either CR, CR+LF, or NEL.
You can use NSString's -componentsSeparatedByString: method, which will return to you an NSArray:
NSURL *url = [NSURL URLWithString:kTextURL];
NSString *response = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding];
textView.text = response;
NSArray *lines = [response componentsSeparatedByString:#"\n"];
//iterate through the lines...
for(NSString *line in lines) {
//do something with line...
}