Use %20 instead of + when encoding for URL query strings, since it appears to be more compatible. (Well, it works better with Micro.blog.)

This commit is contained in:
Brent Simmons 2018-01-14 11:11:53 -08:00
parent b05d2f8f5f
commit 39d6086e0c
4 changed files with 6 additions and 7 deletions

View File

@ -12,7 +12,7 @@ public extension Dictionary {
public func urlQueryString() -> String? { public func urlQueryString() -> String? {
// Turn a dictionary into string like foo=bar&param2=some+thing // Turn a dictionary into string like foo=bar&param2=some%20thing
// Return nil if empty dictionary. // Return nil if empty dictionary.
if isEmpty { if isEmpty {

View File

@ -12,8 +12,7 @@ public extension String {
public func encodedForURLQuery() -> String? { public func encodedForURLQuery() -> String? {
let s = replacingOccurrences(of: " ", with: "+") guard let encodedString = addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
guard let encodedString = s.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return nil return nil
} }
return encodedString.replacingOccurrences(of: "&", with: "%38") return encodedString.replacingOccurrences(of: "&", with: "%38")

View File

@ -15,7 +15,7 @@ class DictionaryTests: XCTestCase {
let d = ["foo": "bar", "param1": "This is a value."] let d = ["foo": "bar", "param1": "This is a value."]
let s = d.urlQueryString() let s = d.urlQueryString()
XCTAssertTrue(s == "foo=bar&param1=This+is+a+value." || s == "param1=This+is+a+value.&foo=bar") XCTAssertTrue(s == "foo=bar&param1=This%20is%20a%20value." || s == "param1=This%20is%20a%20value.&foo=bar")
} }
func testQueryStringWithAmpersand() { func testQueryStringWithAmpersand() {
@ -23,7 +23,7 @@ class DictionaryTests: XCTestCase {
let d = ["fo&o": "bar", "param1": "This is a&value."] let d = ["fo&o": "bar", "param1": "This is a&value."]
let s = d.urlQueryString() let s = d.urlQueryString()
XCTAssertTrue(s == "fo%38o=bar&param1=This+is+a%38value." || s == "param1=This+is+a%38value.&fo%38o=bar") XCTAssertTrue(s == "fo%38o=bar&param1=This%20is%20a%38value." || s == "param1=This%20is%20a%38value.&fo%38o=bar")
} }
func testQueryStringWithAccentedCharacters() { func testQueryStringWithAccentedCharacters() {

View File

@ -16,9 +16,9 @@ class StringTests: XCTestCase {
XCTAssertEqual(s, "foo") XCTAssertEqual(s, "foo")
s = "foo bar".encodedForURLQuery() s = "foo bar".encodedForURLQuery()
XCTAssertEqual(s, "foo+bar") XCTAssertEqual(s, "foo%20bar")
s = "foo bar &well".encodedForURLQuery() s = "foo bar &well".encodedForURLQuery()
XCTAssertEqual(s, "foo+bar+%38well") XCTAssertEqual(s, "foo%20bar%20%38well")
} }
} }