Last active
August 26, 2016 00:52
-
-
Save kaz29/e30ad2b38f4dfcdbc957f0f12e17ea95 to your computer and use it in GitHub Desktop.
Alamofireのカスタムエンコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func makeCustomEncoding() -> ParameterEncoding { | |
return ParameterEncoding.Custom { requestConvertible, parameters in | |
func escape(string: String) -> String { | |
// MEMO: /, ? もエンコードされるようにオリジナルのコードに追加指定している | |
// see https://github.com/Alamofire/Alamofire/blob/master/Source/ParameterEncoding.swift#L220 | |
// | |
let generalDelimitersToEncode = ":#[]@/?" // does not include "?" or "/" due to RFC 3986 - Section 3.4 | |
let subDelimitersToEncode = "!$&'()*+,;=" | |
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet | |
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) | |
var escaped = "" | |
if #available(iOS 8.3, OSX 10.10, *) { | |
escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string | |
} else { | |
let batchSize = 50 | |
var index = string.startIndex | |
while index != string.endIndex { | |
let startIndex = index | |
let endIndex = index.advancedBy(batchSize, limit: string.endIndex) | |
let range = startIndex..<endIndex | |
let substring = string.substringWithRange(range) | |
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring | |
index = endIndex | |
} | |
} | |
return escaped | |
} | |
let mutableURLRequest = requestConvertible.URLRequest | |
guard var parameters = parameters else { | |
return (mutableURLRequest, nil) | |
} | |
for (key, value) in parameters { | |
parameters[escape(key)] = escape("\(value)") | |
} | |
let query = "?" + (parameters.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") | |
mutableURLRequest.URL = NSURL(string: mutableURLRequest.URLString.stringByAppendingString(query)) | |
return (mutableURLRequest, nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment