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
Try to use
stringByAddingPercentEncodingWithAllowedCharacters
method with[NSCharacterSet URLUserAllowedCharacterSet]
it will cover all the casesObjective C
swift
Output
Test%20%2F%20Test
according to the following blog
This one is working for me.
I found the above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/
You can also use this function with swift extension. Please let me know if there is any issue.
In Swift 3, please try out below:
Since,
stringByAddingPercentEscapesUsingEncoding
encodes non URL characters but leaves the reserved characters (like!*'();:@&=+$,/?%#[]
), You can encode the url like the following code:I opted to use the
CFURLCreateStringByAddingPercentEscapes
call as given by accepted answer, however in newest version of XCode (and IOS), it resulted in an error, so used the following instead:Unfortunately,
stringByAddingPercentEscapesUsingEncoding
doesn't always work 100%. It encodes non-URL characters but leaves the reserved characters (like slash/
and ampersand&
) alone. Apparently this is a bug that Apple is aware of, but since they have not fixed it yet, I have been using this category to url-encode a string:Used like this:
This also works:
Some good reading about the subject:
Objective-c iPhone percent encode a string?
Objective-C and Swift URL encoding
http://cybersam.com/programming/proper-url-percent-encoding-in-ios
https://devforums.apple.com/message/15674#15674 http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/