I'm doing this to encode my URL in this way,
but its not working,
i got the result in NSLog but its the same url nothing is changing.
Please help me to sort this issue.
below is my code :
NSString *unencodedUrlString =
[#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#" %#", unencodedUrlString);
Thanks in advance
The comma is a legal URL character, therefore stringByAddingPercentEscapesUsingEncoding leaves "2,7" as it is and does not replace it by "2%2C7".
If you want the comma to be replaced by a percent escape (as I understand from your
comment to the question), you can use CFURLCreateStringByAddingPercentEscapes
instead:
NSString *str = #"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7";
NSString *encoded = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)(str), NULL, CFSTR(","), kCFStringEncodingUTF8));
NSLog(#"%#", encoded);
Output:
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
The fourth parameter CFSTR(",") specifies that the comma should be replaced by
a percent escape even if it is a legal URL character.
Use this
NSString *str = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"];
NSString *path = [str stringByReplacingOccurrencesOfString:#"," withString:#"/"];
NSLog(#"%#",path);
This will do nothing but will make , to /.
Related
for(int i= 0 ;i<[urlsArrray count]; i++)
{
NSString *urlString = [urlsArrray objectAtIndex:i];
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *urlstring1 = [url absoluteString];
NSArray *parts = [urlstring1 componentsSeparatedByString:#"/"];
NSString *fileName = [parts objectAtIndex:[parts count]-1];
NSMutableString *tempString = [NSMutableString stringWithString:fileName];
// [tempString replaceCharactersInRange:[tempString rangeOfString:#"%20"] withString:#" "];
NSLog(#"file name in temp string: %# word name: %#", tempString, wordNameDB);
NSRange match = [tempString rangeOfString:wordNameDB];
if(match.location != NSNotFound)
{
NSLog(#"match found at %u", match.location);
isAvailable = YES;
break;
}
Hi friends, now my problem is i am getting file name from server..., if file name is having any spaces then it replace '%20' ( i.e ex: "hello world" is actual name but i am getting file name like: "hello%20world") .
1. I am not sure all file names having spaces.
2. And also i am not sure a file may have only one space
so first i have to check the file is having spaces or not, if have then i want to replace all "%20" with #" " string. Please give me any suggestions or code snippets.
OR " THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")..... thank you
If you have your file name stored in fileName param, you can use the following:
fileName = [fileName stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
The above code will replace all "%20" with " ". If there are no "%20" in the fileName, you will get back the same string.
Correction:
I was confused with stringByAddingPercentEscapesUsingEncoding mentioned in code and thought you have already used stringByReplacingPercentEscapesUsingEncoding. If you are not using stringByReplacingPercentEscapesUsingEncoding method, you should use that in this case. The above code is useful, only if that is not able to remove any particular string which you want to replace.
What you need is replacing the escape charcters, according to the encoding.
Use this and all your spaces and other URL encoded characters will be converted to what you need.
[#"yourString" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")
Yes, use this:
NSString *newString = [yourstring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Use this to remove spaces ..
urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
You seem to already have a valid NSURL object representing the file. Getting the filename from a URL is easy:
...
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *path = [url path];
NSString *filename = [path lastPathComponent];
No fiddling with unescaping percent escapes, URL parsing, and other error prone stuff.
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"];
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 );
The following code works, but it's ugly and creates a bunch of autoreleased objects. I'm using similar code for parsing reserved HTML characters as well (for quotes, & symbols, etc). I'm just wondering... Is there a cleaner way?
NSString *result = [[NSString alloc] initWithString:userInput];
NSString *result2 = [result stringByReplacingOccurrencesOfString:#"#"
withString:#"\%23"];
NSString *result3 = [result2 stringByReplacingOccurrencesOfString:#" "
withString:#"\%20"];
formatted = [[result3 stringByReplacingOccurrencesOfString:#"&"
withString:#"\%26"] retain];
[result release];
#Yannick, you were on the right track, thank you. stringByAddingPercentEscapesUsingEncoding sort of works but ignores certain characters that can still be a problem (like slashes). Here is the best way to do URL encoding:
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8 );
Have you tried to use the stringByAddingPercentEscapesUsingEncoding method?
formatted = [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I'm trying to send the contents of UITextView or UITextField as parameters to a php file
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",nameField.text, tagsField.text, dreamEntry.text];
When i log urlstr, the url format is ok just as long as the UITextView or UITextField don't contain spaces. How would i go about converting the spaces to %20 ?
edit
here is the code at present, which not only crashes but isn't encoding the url properly.
name=John Doe&tags=recurring nightmare&entry=Testing testing testing
is converted to
name=John -1844684964oe&tags=recurringightmare&entry=Testing 4.214929e-307sting -1.992836e+00sting
- (IBAction)sendButtonPressed:(id)sender
{
NSString *urlString = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#", nameField.text, tagsField.text, dreamEntry.text];
NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:encodedString];
NSLog(encodedString);
NSLog(urlString);
[urlString release];
[url release];
[encodedString release];
}
Actually, all of the previous answers contain at least some inaccuracies, which for many common values of user provided text in the TextFields would not correctly communicate with the server
stringByAddingPercentEscapesUsingEncoding: percent escapes all characters which are not valid URL characters. This method should applied once to the entire URL.
A previous answer claims that stringByAddingPercentEscapesUsingEncoding: works like the URL building classes in many scripting languages, where you should not apply it to the entire URL string, but it doesn't. Anyone can easily verify this by checking its output for unescaped &s and ?s. So it is fine to apply to the entire string, but it is not enough to apply to your 'dynamic' url content.
The previous answer is right in that you have to do some more work to the names and values that go into your CGI query string. Since CGI is specified by RFC3875, this is often referred to as RFC3875 percent escaping. It makes sure that your names and values don't contain characters that are valid URL characters but which are significant in other parts of the URL (;, ?, :, #, &, =, $, +, {, }, <, >, and ,)
However, it is very important to also finish by doing plain URL percent escapes on the full string to make sure that all characters in the string are valid URL characters. While you don't in your example, in general there could be characters in a 'static' part of the string which are not valid URL characters, so you do need to escape those as well.
Unfortunately, NSString doesn't give us the power to escape the RFC3875 significant characters so we have to dip down into CFString to do so. Obviously using CFString is a pain so I generally add a Category onto NSString like so:
#interface NSString (RFC3875)
- (NSString *)stringByAddingRFC3875PercentEscapesUsingEncoding:(NSStringEncoding)encoding;
#end
#implementation NSString (RFC3875)
- (NSString *)stringByAddingRFC3875PercentEscapesUsingEncoding:(NSStringEncoding)encoding {
CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(encoding);
NSString *rfcEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#";/?:#&=$+{}<>,",
cfEncoding);
return [rfcEscaped autorelease];
}
#end
With this Category in place, the original problem could be correctly solved with the following:
NSString *urlEscapedBase = [#"http://server.com/file.php" stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedName = [nameField.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedTags = [tagsField.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedEntry = [dreamEntry.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *urlStr = [NSString stringWithFormat:#"%#?name=%#&tags=%#&entry=%#",
urlEscapedBase,
rfcEscapedName,
rfcEscapedTags,
rfcEscapedEntry];
NSURL *url = [NSURL URLWithString:urlStr];
This is a little variable heavy just be more clear. Also note that the variable list provided to stringWithFormat: should not be nil terminated. The format string describes the precise number of variables that should follow it. Also, technically the strings for query string names (name, tags, entry,..) should be run through stringByAddingPercentEscapesUsingEncoding: as a matter of course but in this small example we can easily see that they contain no invalid URL characters.
To see why the previous solutions are incorrect, imagine that the user input text in dreamEntry.text contains an &, which is not unlikely. With the previous solutions, all text following that character would be lost by the time the server got that text, since the unescaped ampersand would be interpreted by the server as ending the value portion of that query string pair.
You're not supposed to URL-escape the entire string, you're supposed to URL-escape the dynamic components. Try
NSString *urlStr = [NSString stringWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",
[nameField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[tagsField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[dreamEntry.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
nil];
NSURL *url = [NSURL URLWithString:urlStr];
The second issue with your code (and undoubtedly the reason for the odd printing) is you're passing the string directly to NSLog, so it's being treated as a format string. You need to use
NSLog(#"%#", encodedString);
instead. That will make it print as expected.
Edit: A third issue with your code is you're mixing autoreleased and owned objects, then releasing them all at the end. Go look at the 3 objects you create, and which you subsequently release later. One of them shouldn't be released later because it was produced by a method that did not start with the words alloc, copy, or new. Identifying the object in question is an exercise left to the reader.
You can take your URL and use:
NSString *urlStr = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",nameField.text, tagsField.text, dreamEntry.text];
NSString *encStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];