简体   繁体   中英

Solution for passing special characters from iPhone to PHP Script (SQL Database)

OK, after much research, and help with stackoverflow users, I've narrowed down how to fix my problem. Most special characters work, except the ampersand.

So, how can I implement the following code twice? I want to do this

[[tvQ.text stringByReplacingOccurrencesOfString:@"&" withString:@"and"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]

and

[[tvQ.text stringByReplacingOccurrencesOfString:@"\n" withString:@" "] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]

for the same NSString

- (void) doPost:(NSString *)sport {
NSUserDefaults *p = [NSUserDefaults standardUserDefaults];

NSString* string1 = [[p valueForKey:@"user"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* string2 = [[p valueForKey:@"pass"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* string3 = [[[tvQ.text stringByReplacingOccurrencesOfString:@"\n" withString:@" "] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* string4 = [[tvQ.text stringByReplacingOccurrencesOfString:@"&" withString:@"and"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* urlString = [NSString stringWithFormat:@"http://website.com/phpscript.php?user=%@&pass=%@&cat=%@&sub=%@&body=%@",string1,string2,sport,@"",string3,string4];
id val1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
[p setObject:val1 forKey:@"q"];

I'm not sure what I'm doing wrong here so that it respects both arguments defined in string 3 and string4.

Just nest the method that transforms the string:

[[[tvQ.text stringByReplacingOccurrencesOfString:@"&" withString:@"and"] stringByReplacingOccurrencesOfString:@"\n" withString:@" "] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]

Now the string has all '&' replaced by "and", AND all "\\n" replaced by " ", AND it has been processed through stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding to make it safe to pass as a web query.

But remember the problem the last question showed - don't nest too deeply, or it can get very hard to read what you wrote when you later go back to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM