How to escape an NSString to use in NSURL? [closed]

与世无争的帅哥 提交于 2020-01-14 07:28:32

问题


Got this code so far for my send button:

NSString* urlString = [NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", messageBox.text stringByAddingPercentEscapesUsingEncoding : NSUFT8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];

However I do get the error "Expected ':'


回答1:


You need to separate the two string construction calls

NSString* urlString = [[NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];



回答2:


The proper way is not to escape the entire URL. You should only escape individual parameter values.

NSString* urlString = [NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", [messageBox.text stringByAddingPercentEscapesUsingEncoding : NSUFT8StringEncoding]];

Better yet, for readability and easier debugging, do this:

NSString *escapedText = [messageBox.text stringByAddingPercentEscapesUsingEncoding:NSUFT8StringEncoding];
NSString* urlString = [NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", escapedText];



回答3:


Try:

NSString* urlString = [[NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUFT8StringEncoding];



回答4:


Separate the NSString method to see it clearly:

NSString* urlString = [[NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUFT8StringEncoding];



回答5:


NSURL will automatically url encode the string when you call NSURL urlWithString this code is not needed.



来源:https://stackoverflow.com/questions/13014398/how-to-escape-an-nsstring-to-use-in-nsurl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!