Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Alamofireのカスタムエンコード
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