I have a URL string (NSString
) with spaces and &
characters. How do I url encode the entire string (including the &
ampersand character and spaces)?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- Could I create “Call” button in HTML 5 IPhone appl
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
ios 7 update
This might be helpful
For iOS 7+, the recommended way is:
You can choose the allowed character set as per the requirement of the URL component.
After reading all the answers for this topic and the (wrong) accepted one, I want to add my contribution.
IF the target is iOS7+, and in 2017 it should since XCode makes really hard to deliver compatibility under iOS8, the best way, thread safe, fast, amd will full UTF-8 support to do this is:
(Objective C code)
This will extend NSString, will exclude RFC forbidden characters, support UTF-8 characters, and let you use things like:
That will print on your debug console:
... note also the use of dispatch_once to avoid multiple initializations in multithread environments.
I faced a similar problem passing complex strings as a POST parameter. My strings can contain Asian characters, spaces, quotes and all sorts of special characters. The solution I eventually found was to convert my string into the matching series of unicodes, e.g. "Hu0040Hu0020Hu03f5...." using [NSString stringWithFormat:@"Hu%04x",[string characterAtIndex:i]] to get the Unicode from each character in the original string. The same can be done in Java.
This string can be safely passed as a POST parameter.
On the server side (PHP), I change all the "H" to "\" and I pass the resulting string to json_decode. Final step is to escape single quotes before storing the string into MySQL.
This way I can store any UTF8 string on my server.
New APIs have been added since the answer was selected; You can now use NSURLUtilities. Since different parts of URLs allow different characters, use the applicable character set. The following example encodes for inclusion in the query string:
To specifically convert '&', you'll need to remove it from the url query set or use a different set, as '&' is allowed in a URL query:
Swift 2.0 Example (iOS 9 Compatiable)