Skip to content

Instantly share code, notes, and snippets.

@kaz29 kaz29/custom_encode.swift
Last active Aug 26, 2016

Embed
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.