ios - how do I concatinate strings to create a url? - objective-c

I am trying to make a url by first collecting the parameters, and then in one statement creating the actual url. Here is what I am trying to do:
NSString *urlString = #"http://www.some_login_url.com?email=%#&password=%#";
NSString *email = self.email.text;
NSString *password = self.password.text;
NSString *url_to_send = [NSString stringWithFormat:#"%#%#", urlString , email , password];
So what I wanted to do was replace the # symbols with the values in the variables, but instead the second variable just got appended to the end of the string.
How would I change the last line so I could put the right parameters in their correct spots?
Thanks!!

I think you meant:
NSString *url_to_send = [NSString stringWithFormat:urlString , email , password];
But you might want to look for ways to construct a URL that do proper escaping of arguments, etc. For example, see this question.

The urlString is your format, so you want:
NSString *url_to_send = [NSString stringWithFormat:urlString , email , password];

Related

Append variables to string in Objective-C [duplicate]

How can I combine "stringURL" and "stringSearch" together?
- (IBAction)search:(id)sender;{
stringURL = #"http://www.websitehere.com/index.php?s=";
stringSearch = search.text;
/* Something such as:
stringURL_ = stringURL + stringSearch */
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:stringURL_]]];
}
Philippe gave a good example.
You can also use plain stringWithFormat: method.
NSString *combined = [NSString stringWithFormat:#"%#%#", stringURL, stringSearch];
This way you can manipulate string even more by putting somethig inbetween the strings like:
NSString *combined = [NSString stringWithFormat:#"%#/someMethod.php?%#", stringURL, stringSearch];
NSString* combinedString = [stringUrl stringByAppendingString: search.text];
NSString * combined = [stringURL stringByAppendingString:stringSearch];
Instead of stringByAppendingString:, you could also use
NSString *combined = [NSString stringWithFormat: #"%#%#",
stringURL, stringSearch];
This is especially interesting/convenient if you have more than one string to append. Otherwise, the stringbyAppendingString: method is probably the better choice.
You can use stringByAppendingString:
stringURL = [#"http://www.websitehere.com/index.php?s="
stringByAppendingString:search.text];
If you want to have some control about the format of the parameter you should assemble
your URL string with
[NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text]
This solution is charming because you can append almost anything which can be inserted into a printf-style format.
I would not have given the answer of such general question.
There are many answers of same type question have already given. First find the answer of your question from existing question.
NSString* myURLString = [NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text];

stringByAddingPercentEscapesUsingEncoding does not escape "&"

I am using stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding to pass data to a php script. The problem is if the field has the char '&' in the text lets say: 'someone & cars', only the text "someone" is saved, everything after the '&' doesn't.
To create the string I use [NSString stringWithFormat:], so I have like 5 field in the form and if I use stringbyReplacingOcorrencesOfstring:#"&", what it does is replace the whole string not only the char '&' from the text field, so I get error.
Any ideas?
Unfortunately, stringByAddingPercentEscapesUsingEncoding: doesn't actually escape all necessary URL characters.
Instead, you can use the lower-level CoreFoundation function:
(NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)myString, NULL, (CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding));
or, when using ARC:
CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)myString, NULL, (__bridge CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding)));
See this post for an example of a category on NSString that uses this function.
Following works using stringByAddingPercentEncodingWithAllowedCharacters if you want to specifically allow what would be encoded yourself. I'm using after base64 so this works fine.
NSString *charactersToEscape = #"!*'();:#&=+$,/?%#[]\" ";
NSCharacterSet *customEncodingSet = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *url = [NSString stringWithFormat:#"%#", #"http://www.test.com/more/test.html?name=john&age=28"];
NSString *encodedUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:customEncodingSet];

How to Use An Escape URL String With Formatting in Objective-C

I need to gather data from a website based on the user's input.
searchString is the user inputted value, such as "search this string".
NSString *withoutSpaces = [searchString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Here, I need to replace spaces with %20
Next, I need to put the new string without spaces (replaced with %20) into another string.
NSString *unescapedSearchString = [NSString stringWithFormat:
#"website.com/query?=%22%#%22", withoutSpaces];
The site I need is not really "website.com", but that's just an example. I also need the %22 to remain at the beginning and end.
As you can see, I need the %# to format the new withoutSpaces user input into the website URL.
I did a search and found examples but I could not find any with formatting such as in my case using %#.
What's the best way to "escape" the characters and keep my formatted string? Currently, when I try to access data from the website, it comes back as null. However, when I try a string without the %# formatting and an actual value, I successfully retrieve the data from a website.
Any help is greatly appreciated.
You should do things this way:
NSString *searchString = ... // the raw search string with spaces and all
NSString *quoted = [NSString stringWithFormat:#"\"%#\"", searchString];
NSString *escaped = [quoted stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"website.com?query=%#&value=all", escaped];
BTW - the URL seems a little off. There should be a variable name before the = and after the ?.

stringByAppendingFormat not working

I have an NSString and fail to apply the following statement:
NSString *myString = #"some text";
[myString stringByAppendingFormat:#"some text = %d", 3];
no log or error, the string just doesn't get changed. I already tried with NSString (as documented) and NSMutableString.
any clues most welcome.
I would suggest correcting to (documentation):
NSString *myString = #"some text";
myString = [myString stringByAppendingFormat:#" = %d", 3];
From the docs:
Returns a string made by appending to the receiver a string constructed from a given format string and the following arguments.
It's working, you're just ignoring the return value, which is the string with the appended format. (See the docs.) You can't modify an NSString — to modify an NSMutableString, use -appendFormat: instead.
Of course, in your toy example, you could shorten it to this:
NSString *myString = [NSString stringWithFormat:#"some text = %d", 3];
However, it's likely that you need to append a format string to an existing string created elsewhere. In that case, and particularly if you're appending multiple parts, it's good to think about and balance the pros and cons of using a mutable string or several immutable, autoreleased strings.
Creating strings with #"" always results in immutable strings. If you want to create a new NSMutableString do it as following.
NSMutableString *myString = [NSMutableString stringWithString:#"some text"];
[myString appendFormat:#"some text = %d", 3];
I had a similar warning message while appending a localized string. This is how I resolved it
NSString *msgBody = [msgBody stringByAppendingFormat:#"%#",NSLocalizedString(#"LOCALSTRINGMSG",#"Message Body")];

simple question concerning NSString adding multiple strings

I have a fairly simple question concerning NSString however it doesn't seem to do what I want.
this is what i have
NSString *title = [NSString stringWithformat: character.name, #"is the character"];
This is a line in my parser takes the charactername and inserts in into a plist , however it doesn't insert the #"is the character" is there something I'm doing wrong?
Your code is wrong. It should be :
NSString *title
= [NSString stringWithformat:#"%# is the character", character.name];
assuming that character.name is another NSString.
Read the Formatting String Objects paragraph of the String Programming Guide for Cocoa to learn everything about formatting strings.
stringWithFormat takes a format string as the first argument so, assuming character.name is the name of your character, you need:
NSString *title = [NSString stringWithformat: #"%s is the character",
character.name];
What you have is the character name as the format string so, if it's #"Bob" then Bob is what you'll get. If it was "#Bob %s", that would work but would probably stuff up somewhere else that you display just the character name :-)
Note that you should use "%s" for a C string, I think "%#" is the correct format specifier if character.name is an NSString itself.